Hawke
Hawke

Reputation: 584

Fluent Validator for when another property is true

I am trying to use FluentValidation to validate the property 'Username' if another property 'Found' is true.

Object Contains:
   string Username
   bool Found

RuleFor(x => x.Username)
    .NotEmpty().DependentRules(() => {
                RuleFor(y => y.Found).Equals(true); //Not valid syntax
            })
    .WithMessage("Not Found");

Unfortunately, there seems to be no easy way to do this?

Upvotes: 3

Views: 4563

Answers (1)

rgvlee
rgvlee

Reputation: 3183

Use the When clause.

RuleFor(x => x.Username).NotEmpty().When(x => x.Found);

Working example

The dependent rules is a bit different; basically the rules specified in the dependent rules block will only be tested if the rule they're attached to passes.

As per the doco

RuleFor(x => x.Surname).NotNull().DependentRules(() => {
  RuleFor(x => x.Forename).NotNull();
});

Here the rule against Forename will only be run if the Surname rule passes.

Upvotes: 9

Related Questions