Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 960
Enixf Avatar asked Mar 09 '23 01:03

Enixf


1 Answers

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());
    }
}
like image 180
Federico Dipuma Avatar answered Apr 09 '23 00:04

Federico Dipuma