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

前端 未结 1 1708
时光说笑
时光说笑 2021-01-14 04:34

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

相关标签:
1条回答
  • 2021-01-14 05:17

    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());
        }
    }
    
    0 讨论(0)
提交回复
热议问题