Fluent Validation For .NET

时间:2023-03-08 18:26:26
//.net 中数据验证,一个开源的项目,直接下载
1 using FluentValidation; public class CustomerValidator: AbstractValidator<Customer> {
public CustomerValidator() {
RuleFor(customer => customer.Surname).NotEmpty();
RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Please specify a first name");
RuleFor(customer => customer.Discount).NotEqual().When(customer => customer.HasDiscount);
RuleFor(customer => customer.Address).Length(, );
RuleFor(customer => customer.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
} private bool BeAValidPostcode(string postcode) {
// custom postcode validating logic goes here
}
} Customer customer = new Customer();
CustomerValidator validator = new CustomerValidator();
ValidationResult results = validator.Validate(customer); bool validationSucceeded = results.IsValid;
IList<ValidationFailure> failures = results.Errors;