a. Index Documentation table of contents b. Creating a Validator 定义对象,及对象验证类
public class Customer { public int Id { get; set; } public string Surname { get; set; } public string Forename { get; set; } public decimal Discount { get; set; } public Address Address { get; set; } public List AddressLines { get; set; } = new List(); public IList Orders { get; set; } }
///
/// 为Customer类定义一组规则,继承自AbstractValidator ///
public class CustomerValidator : AbstractValidator
{ public CustomerValidator() { //多个验证规则 RuleFor(customer => customer.Surname).NotNull().NotEqual("foo");
public class Address { public string Line1 { get; set; } public string Line2 { get; set; } public string Town { get; set; } public string County { get; set; } public string Postcode { get; set; } } public class AddressValidator : AbstractValidator { public AddressValidator() { RuleFor(address => address.Postcode).NotNull(); //etc } }
public class Order { public string ProductName { get; set; } public decimal? Cost { get; set; } } public class OrderValidator : AbstractValidator { public OrderValidator() { RuleFor(x => x.ProductName).NotNull(); RuleFor(x => x.Cost).GreaterThan(0); } }
调用
public void Validate() { Customer customer = new Customer(); customer.Orders = new List { new Order { ProductName = "Foo" }, new Order { Cost = 5 } };
CustomerValidator validator = new CustomerValidator(); ValidationResult results = validator.Validate(customer);
//将复杂的验证定义分解到较小的片段中,可独立使用 //把多个规则聚集都一个规则集合中 var result1 = validator.Validate(customer, ruleSet: "Names"); //多个规则集合 var result2 = validator.Validate(customer, ruleSet: "Names,MyRuleSet,SomeOtherRuleSet"); //不在任何规则集合中的default var result3 = validator.Validate(customer, ruleSet: "default,MyRuleSet");
//Ensures that the specified property is not null. RuleFor(customer => customer.Surname).NotNull();
//Ensures that the specified property is not null, an empty string or whitespace (or the default value for value types, eg 0 for int) RuleFor(customer => customer.Surname).NotEmpty();
//Not equal to a particular value RuleFor(customer => customer.Surname).NotEqual("Foo"); //Not equal to another property RuleFor(customer => customer.Surname).NotEqual(customer => customer.Forename);
//Equal to a particular value RuleFor(customer => customer.Surname).Equal("Foo"); //Equal to another property RuleFor(customer => customer.Password).Equal(customer => customer.PasswordConfirmation);
//must be between 1 and 250 chars (inclusive) RuleFor(customer => customer.Surname).Length(1, 250);
//Less than a particular value RuleFor(customer => customer.CreditLimit).LessThan(100); //Less than another property RuleFor(customer => customer.CreditLimit).LessThan(customer => customer.MaxCreditLimit);
//Less than a particular value RuleFor(customer => customer.CreditLimit).LessThanOrEqualTo(100); //Less than another property RuleFor(customer => customer.CreditLimit).LessThanOrEqualTo(customer => customer.MaxCreditLimit);
//Greater than a particular value RuleFor(customer => customer.CreditLimit).GreaterThan(0); //Greater than another property RuleFor(customer => customer.CreditLimit).GreaterThan(customer => customer.MinimumCreditLimit);
//Greater than a particular value RuleFor(customer => customer.CreditLimit).GreaterThanOrEqualTo(1); //Greater than another property RuleFor(customer => customer.CreditLimit).GreaterThanOrEqualTo(customer => customer.MinimumCreditLimit);
//Passes the value of the specified property into a delegate that can perform custom validation logic on the value //Also known as "Must" RuleFor(customer => customer.Surname).Must(surname => surname == "Foo"); //Note that there is an additional overload for Must that also accepts an instance of the parent object being validated. //This can be useful if you want to compare the current property with another property from inside the predicate: //Note that in this particular example, it would be better to use the cross-property version of NotEqual RuleFor(customer => customer.Surname).Must((customer, surname) => surname != customer.Forename);
//Ensures that the value of the specified property matches the given regular expression. Example: RuleFor(customer => customer.Surname).Matches("some regex here");
//Ensures that the value of the specified property is a valid email address format. Example: RuleFor(customer => customer.Email).EmailAddress();
d. Configuring a Validator 配置验证器 1.Override the default error message
RuleFor(customer => customer.Surname).NotNull().WithMessage("Please ensure that you have entered your Surname"); //‘{PropertyName}‘ will be replaced with the name of the property being validated //and the value ‘Surname‘ will be inserted. RuleFor(customer => customer.Surname).NotNull().WithMessage("Please ensure you have entered your {PropertyName}");
The placeholders are Used in all validators: ‘{PropertyName}‘ - The name of the property being validated ‘{PropertyValue}‘ - The value of the property being validated These include the predicate validator(‘Must‘ validator), the email and the regex validators.
Used in comparison validators: (Equal, NotEqual, GreaterThan, GreaterThanOrEqual, etc.) { ComparisonValue} = Value that the property should be compared to
Used only in the Length validator: { MinLength} = Minimum length { MaxLength} = Maximum length { TotalLength} = Number of characters entered
//Using static values in a custom message: RuleFor(customer => customer.Surname).NotNull() .WithMessage(customer => string.Format("This message references some constant values: {0} {1}", "hello", 5)); //Result would be "This message references some constant values: hello 5"
//Referencing other property values: RuleFor(customer => customer.Surname).NotNull() .WithMessage(customer => $"This message references some other properties: Forename: {customer.Forename} Discount: {customer.Discount}"); //Result would be: "This message references some other properties: Forename: Jeremy Discount: 100"
2.Overriding the Default Property Name
//The default error message would be ‘Surname‘ must not be empty. RuleFor(customer => customer.Surname).NotNull(); //Replace just the property name by calling WithName //Now the error message would be ‘Last name‘ must not be empty. RuleFor(customer => customer.Surname).NotNull().WithName("Last name"); //Completely rename the property, including the Errors collection on the ValidationResult RuleFor(customer => customer.Surname).NotNull().OverridePropertyName("Last name");
//Property name resolution is also pluggable.By default, the name of the property extracted from the MemberExpression passed to RuleFor. If you want change this logic, you can set the DisplayNameResolver property on the ValidatorOptions class. //这段不是太懂 ValidatorOptions.DisplayNameResolver = (type, member) => { if (member != null) { return member.Name + "Foo"; } return null; };
//另外,FluentValidation 可采用 DisplayName and Display attributes,来生成错误信息中的属性名,同 WithName public class Person { [Display(Name = "Last name")] public string Surname { get; set; } }
The two cascade modes are: Continue(the default) - always invokes all validators in a rule definition StopOnFirstFailure - stops executing a rule as soon as a validator fails
//在单个验证器类中设置级联模式 public class PersonValidator : AbstractValidator { public PersonValidator() { // First set the cascade mode CascadeMode = CascadeMode.StopOnFirstFailure;
e. Custom Validators 定制验证器 1.Using the Predicate Validator 使用断言验证器
public class Person { public IList Pets { get; set; } = new List(); } public class PersonValidator : AbstractValidator { public PersonValidator() { RuleFor(x => x.Pets).Must(list => list.Count <= 10).WithMessage("The list must contain fewer than 10 items"); } }
//封装成扩展方法,使其可重用 public static class MyCustomValidators { public static IRuleBuilderOptions<T, IList> ListMustContainFewerThan(this IRuleBuilder<T, IList> ruleBuilder, int num) { return ruleBuilder.Must(list => list.Count < num).WithMessage("The list contains too many items"); } } RuleFor(x => x.Pets).ListMustContainFewerThan(10);
Using a custom message placeholder 定制消息
//The resulting message will now be ‘Pets‘ must contain fewer than 10 items. public static IRuleBuilderOptions<T, IList> ListMustContainFewerThan(this IRuleBuilder<T, IList> ruleBuilder, int num) { return ruleBuilder.Must((rootObject, list, context) => { context.MessageFormatter.AppendArgument("MaxElements", num); return list.Count < num; }) .WithMessage("{PropertyName} must contain fewer than {MaxElements} items."); }
return list.Count < num; }) .WithMessage("{PropertyName} must contain fewer than {MaxElements} items. The list contains {TotalElements} element"); }
2.Using a Custom Validator 使用定制验证器
//This method allows you to manually create the ValidationFailure instance associated with the validation error. RuleFor(x => x.Pets).Custom((list, context) => { if (list.Count > 10) { context.AddFailure("The list must contain 10 items or fewer"); // It allows you to return multiple errors for the same rule context.AddFailure("SomeOtherProperty", "The list must contain 10 items or fewer"); // Or you can instantiate the ValidationFailure directly: context.AddFailure(new ValidationFailure("SomeOtherProperty", "The list must contain 10 items or fewer"); } });
3.Writing a Custom, reusable Property Validator 使用定制可重用属性验证器
//若定制的逻辑非常复杂,则可将定制逻辑放入单独的验证类中 public class ListCountValidator : PropertyValidator { private int _max;
public ListCountValidator(int max) : base("{PropertyName} must contain fewer than {MaxElements} items.") { _max = max; }
protected override bool IsValid(PropertyValidatorContext context) { var list = context.PropertyValue as IList;