Home > Software engineering >  How check other property use custom rule in fluent validation
How check other property use custom rule in fluent validation

Time:01-16

Let's say there is a class and I need to check the value of property 1 against the value of property 2 so that it can be reused. I don't understand how you can pass the value of 2 properties to a custom validation rule of 1 property using fluent validation

I have class

public class MyClass
{
    public string Property1 { get; set; }  
    public string Property2 {get; set; }     
    public string Property3 { get; set; } 
} 

and validato class

public class MyClassValidator : AbstractValidator<MyClass>
{
    public MyClassValidator ()
    {
        RuleFor(мyClass => мyClass.Property1).Property1();
    }
}

and custom rule

public static IRuleBuilderOptions<T, string>
    Property1<T>(this IRuleBuilder<T, string> ruleBuilder)
    {
        return ruleBuilder.NotNull()
                          .NotEmpty()
                          .Length(12)
    }

I want the rule

public static IRuleBuilderOptions<T, string>

    Property1<T>(this IRuleBuilder<T, string> ruleBuilder)
    {
        return ruleBuilder.Custom((x, c) => {
        if(x.Property2== "qwerty")
         if(x.Property1=="q")
          context.AddFailure("")
        });
    }

How can i pass property value of Property2 to Property1 property check?

Edit1 I want this check to be used on other classes

I just want to thank you for your reply. So I decided not only to look at the answers, but also to ask my first question

CodePudding user response:

You need a custom validator. To quote an example from the docs...

public class PersonValidator : AbstractValidator<Person> {
  public PersonValidator() {
   RuleFor(x => x.Pets).Custom((list, context) => {
     if(list.Count > 10) {
       context.AddFailure("The list must contain 10 items or fewer");
     }
   });
  }
}

The context gives you access to the whole object being validated, so you can get at any other properties you want.

  • Related