简体   繁体   English

在没有包装对象的情况下使用 FluentValidation 验证对象列表的最佳方法

[英]Best way to validate a list of objects with FluentValidation without wrapper object

FluentValidation has the possibility to validate collections as described in the documentation . FluentValidation 可以按照文档中的描述验证集合。 However all the examples speak of collections inside an object like:然而,所有示例都谈到了对象内部的集合,例如:

public class Person 
{
  public List<string> AddressLines { get; set; } = new List<string>();
}

I am wondering what the best way is to validate a List<Person> when the collection is not inside an object:我想知道当集合不在对象内时验证List<Person>的最佳方法是什么:

public List<Person> GetPersonsAndValidate()
{
    List<Person> persons = GetPersons();
    // Perform validation
    // Do something with the validation
    return persons;
}

or in a ASP.NET Core controller:或在 ASP.NET Core 控制器中:

[HttpPost]
public IActionResult DoSomething(List<Person> persons)
{
    if (!ModelState.IsValid)
    {
        // Do something with the invalid model, but is it validated?
    }
}

I see two options here, where the second option is not suitable for the second example:我在这里看到两个选项,其中第二个选项不适合第二个示例:

  1. Create a validator on IEnumerable<Person> like:IEnumerable<Person>上创建一个验证器,例如:
public class PersonsValidator : AbstractValidator<IEnumerable<Person>>
{
    public PersonsValidator()
    {
        RuleForEach(x => x).SetValidator(new PersonValidator());
    }

}
  1. Call the person validator directly by looping over the list:通过遍历列表直接调用人员验证器:
foreach (var person in persons)
{
    // I know, the creation of the validator can go outside the foreach...
    var result = new PersonValidator().Validate(person);
    // do something with the result
}
  1. Wrap it inside a parent object anyways (which then needs a validator as well...)无论如何将它包装在父对象中(然后也需要一个验证器......)

Are these the only options, or are there other ways to do this?这些是唯一的选择,还是有其他方法可以做到这一点?

If you set the property ImplicityValidateChildProperties to true in the fluent validation configuration that should do it.如果您在流畅的验证配置中将属性 ImplicityValidateChildProperties 设置为 true,则应该这样做。

        services
            .AddControllers()
            .AddFluentValidation(
                config =>
                {
                    config.AutomaticValidationEnabled = true;
                    config.ImplicitlyValidateChildProperties = true;
                    config.ValidatorOptions.CascadeMode = CascadeMode.Continue;
                })
            .AddNewtonsoftJson();

This automatically validates children properties which in this case is each Person object within the collection.这会自动验证子属性,在本例中是集合中的每个 Person 对象。 I know this works with ICollection but have not tested it with Arrays.我知道这适用于 ICollection,但尚未使用 Arrays 对其进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM