我试图找到 FluentValidation 中是否有可用的方法,允许在根级别验证集合的验证器。
例如如下所示,验证器可用于CustomerValidator
为一堂课Customer
。
使用 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(0).When(customer => customer.HasDiscount);
RuleFor(customer => customer.Address).Length(20, 250);
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;
问题是,如果我有一个List<Customer>
我需要验证至少一个客户应该有Surname
我如何验证该列表。fluidvalidation 是否有开箱即用的功能,目前,我可以考虑以下两种方式。您能建议什么是最好的方法吗?
1.循环迭代,然后为每个客户调用 validate 方法。
List<ValidationResult> listOfValidationErrors = List<ValidationResult>();
// listCustomer is of type List<Customer>
foreach (var customer in listCustomer)
{
CustomerValidator validator = new CustomerValidator();
listOfValidationErrors.Add(validator.Validate(customer);
}
2.为 Customer 集合创建一个新的集合类CustomerCollection
然后创建一个验证器类CustomerCollectionValidator
public class CustomerCollection
{
public List<Customer> ListOfCustomers { get; set; }
public CustomerCollection(List<Customer> listOfCustomers )
{
this.ListOfCustomers = listOfCustomers ;
}
}
然后是验证器类
public class CustomerCollectionValidator: CompositeValidator<CustomerCollection>
{
public CustomerCollectionValidator()
{
RuleFor(x => x.ListOfCustomers)
.Must(ShouldHaveOneSurName)
.WithMessage("Should have one Surname in list");
RuleForEach(x => x.ListOfCustomers).SetValidator<CustomerValidator>();
}
public bool ShouldHaveOneSurName(List<Customer> lstCustomers)
{
if (lstCustomers== null)
{
return false;
}
return lstCustomers.Any(x => !String.IsNullOrWhiteSpace(x.SurName);
}
}