Fluent Validation, different validation for each item in a list in Asp.NET Core

╄→гoц情女王★ 提交于 2019-12-01 08:29:20

问题


I´ve been trying to find a way to validate items inside a list, each with different validation rules. I came upon Fluent validation which is a great library but I can´t seem to find a way to do validation for each item individually. I got a faint idea from this similar thread (Validate 2 list using fluent validation), but I´m not sure how to focus it how I want.

So I have this View Model:

 public class EditPersonalInfoViewModel
{
    public IList<Property> UserPropertyList { get; set; }
}

This contains a list of Active Directory properties. Each represented by this class:

   public class Property
{
    public string Name { get; set; }
    public UserProperties Value { get; set; }
    public string input { get; set; }
    public bool Unmodifiable  { get; set; }
    public string Type { get; set; }
}

The point is that, each AD property has different constraints so I want to specify different rules for each property in the list in some way like this:

   public class ADPropertiesValidator : AbstractValidator<EditPersonalInfoViewModel>
{
    public ADPropertiesValidator()
    {
        RuleFor(p => p.UserPropetyList).Must((p,n) =>
         {
              for (int i = 0; i < n.Count; i++)
                  {
                     if ((n[i].Name.Equals("sAMAccountName"))
                        {
                          RuleFor(n.input ).NotEmpty()....
                        }
                     else if(...)
                        {
                      //More Rules
                        }
                  }
          )

    }
}

Any ideas how to approach this? thanks in advance.


回答1:


You are approaching the validation from the wrong perspective. Instead of creating validation conditions inside your collection container class, just create another validator specific for your Property class, and then use that inside your ADPropertiesValidator:

public class ADPropertyValidator : AbstractValidator<Property>
{
    public ADPropertyValidator()
    {
        When(p => p.Name.Equals("sAMAccountName"), () =>
        {
            RuleFor(p => p.input)
                .NotEmpty()
                .MyOtherValidationRule();
        });

        When(p => p.Name.Equals("anotherName"), () =>
        {
            RuleFor(p => p.input)
                .NotEmpty()
                .HereItIsAnotherValidationRule();
        });
    }
}

public class ADPropertiesValidator : AbstractValidator<EditPersonalInfoViewModel>
{
    public ADPropertiesValidator()
    {
        RuleForEach(vm => vm.UserPropertyList)
            .SetValidator(new ADPropertyValidator());
    }
}


来源:https://stackoverflow.com/questions/46285434/fluent-validation-different-validation-for-each-item-in-a-list-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!