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

懵懂的女人 提交于 2019-12-01 11:26:38

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