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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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());
}
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0