gpt4 book ai didi

c# - 我应该在 FluentValidation 中为 Collection 创建一个新类型吗?

转载 作者:太空狗 更新时间:2023-10-30 01:16:06 28 4
gpt4 key购买 nike

我正在尝试查找 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我如何验证列表。 在 fluentvalidation 中是否有开箱即用的功能,此时,我可以考虑以下两种方法之一。 您能建议什么是最好的方法吗?

1.循环迭代,然后为每个客户调用验证方法。

 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 ;
}
}

然后是Validator类

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 还推荐了另一种方法 here ,它使用继承自 AbstractValidator<List<Customer>> .这不适用于原始代码,但 Jeremy 在 6.3 版中提交了 Fluent Validation 源代码的更改 here .

以下代码展示了对根级别集合进行验证的第三种方法。

public class CustomerCollectionValidator : AbstractValidator<List<Customer>> {
public CustomerCollectionValidator() {
RuleFor(list => list).SetCollectionValidator(new CustomerValidator());
}
}

关于c# - 我应该在 FluentValidation 中为 Collection 创建一个新类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36658385/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com