我应该在FluentValidation中为Collection创建一个新类型吗
本文关键字:一个 新类型 类型 FluentValidation 中为 Collection 创建 我应该 | 更新日期: 2024-09-25 07:06:11
我正在努力寻找FluentValidation中是否有可用的方法,允许在根级别为Validator验证集合。
例如,如下所示,一个验证器可用于类Customer
的CustomerValidator
。使用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
,我该如何验证列表在fluentvalidation中是否存在开箱即用的函数性,此时,我可以考虑以下方法之一<你能建议什么是最好的方法吗>你能建议什么是最好的方法吗>
1.在循环中迭代,然后为每个Customer调用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.为客户集合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);
}
}
除了上述两种方法外,Jeremy Skinner在这里提出了另一种方法,它使用从AbstractValidator<List<Customer>>
继承的方法。这对原始代码不起作用,但Jeremy在这里提交了6.3版Fluent Validation源代码的更改。
以下代码提供了对根级别集合进行验证的第三种方法。
public class CustomerCollectionValidator : AbstractValidator<List<Customer>> {
public CustomerCollectionValidator() {
RuleFor(list => list).SetCollectionValidator(new CustomerValidator());
}
}