新增一個Validator Class,撰寫驗證要輸入的欄位
public XXXValidator() { RuleFor(x => x.xxxfiled).NotEmpty().WithMessage("請輸入欄位"); }
DI注入Service
services.AddTransient<IValidator<AAAViewModel>, XXXValidator>();
然後前端驗證
FluentValidation.Results.ValidationResult vResult = this._xxxValidator.Validate(model); if (!vResult.IsValid) { throw new Exception(Function_ModelStateError.FormatToString(vResult)); }
但是如果有另一個Service也是要用AAAViewModel但是驗證的欄位不一樣呢?
先新增一個Class如下
//來源https://stackoverflow.com/questions/11607476/two-validators-for-one-model public static class ValidationExtensions { public static FluentValidation.Results.ValidationResult ValidateModel<TModel, TValidator>(this TModel model, TValidator validator, ModelStateDictionary modelState) where TModel : class where TValidator : AbstractValidator<TModel> { var result = validator.Validate(model); return result; } }
新增另一個Validator Class,撰寫驗證要輸入的欄位
public YYYValidator() { RuleFor(x => x.yyyfiled).NotEmpty().WithMessage("請輸入欄位"); }
DI注入另一個Service
services.AddTransient<IValidator<AAAViewModel>, YYYValidator>();
然後前端驗證
FluentValidation.Results.ValidationResult vResult = model.ValidateModel(new YYYValidator(), ModelState);//修改這 if (!vResult.IsValid) { throw new Exception(Function_ModelStateError.FormatToString(vResult)); }
參考來源
Two Validators for one Models