我应该在FluentValidation中为集合创建一个新的类型吗? [英] Should i create a new Type for Collection in FluentValidation?

查看:65
本文介绍了我应该在FluentValidation中为集合创建一个新的类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试寻找FluentValidation中是否有可用的方法来允许在根级别对验证器进行验证.

I am trying to find if there is way available in FluentValidation which allows a collection to be validated for a Validator at Root Level.

例如如下所示,对于Customer类,对于CustomerValidator可以使用验证器. 使用FluentValidation;

For e.g. As shown below, a validator is available for CustomerValidator for a class Customer. 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(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中,目前,我可以考虑以下两种方式之一. 您能建议什么是最好的方法吗?

The question is, If i have a List<Customer> and i need to validate that atleast one customer should have Surname how do i validate the list. Is there a out of box functinality available in fluentvalidation, at this time, i can think either of following ways. Can you suggest what can be best approach ?

1..循环进行迭代,然后为每个客户调用validate方法.

1. Iterating in a loop and then calling the validate method for each Customer.

 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

2. Create a new collection class for Customer collection CustomerCollection and then create a validator class 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源代码中的更改. .

Apart from the above 2 methods, Jeremy Skinner suggested another method here, which uses inheritance from AbstractValidator<List<Customer>> . This didn't work with original code, but Jeremy committed the change in Fluent Validation source code in version 6.3 here.

以下代码介绍了验证根级别集合的第三种方法.

Following code presents the 3rd way for doing the validation for Root Level collection.

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

这篇关于我应该在FluentValidation中为集合创建一个新的类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆