FluentValidation that involves 2 properties in the object being validated

Viewed 5491

I have a business rule that says that PropertyA should be a multiple of PropertyB.

As you see, the validation isn't taking care of a property alone, but needs to validate 2 interrelated properties. How do I make this using FluentValidations?

1 Answers

Say you have an object like this:

class Data {
  public int PropertyA;
  public int PropertyB;
}

Then in the validator you can do something like this:

public class DataValidator : AbstractValidator<Data> {

  public DataValidator() {
    // 'x' in this case is the instance of the 'Data' class being validated
    //
    RuleFor(x => x).Must(HaveMultiplierRelationship);
  }

  private bool HaveMultiplierRelationship(Data d)
  {
    return (d.PropertyA % d.PropertyB) == 0;
  }
}

This method works well because you can chain multiple Must calls together to test a number of different aspects of the object in question.

Related