'Conditionally executing rule with FluentValidation for .NET
I'm using FluentValidation for .NET
I have these three rules:
RuleFor(customer => customer.Name).NotEmpty();
RuleFor(customer => customer.Phone).NotEmpty();
RuleFor(customer => customer.Birthday).NotEmpty();
And I want to execute this one only if the three others are validated successfully.
RuleFor(customer => customer).Must(IsUnique).WithMessage("...");
My requirement is not to use Chaining Validators like here because the first three will not be evaluated if the previous of each one failed validation.
What I want is if one of the first three are empty, to display to the user the required fields. If all three are not empty, then I want to validate the last one.
Solution 1:[1]
RuleFor(customer => customer)
.Must(IsUnique)
.WithMessage("...")
.When(x => !string.IsNullOrEmpty(x.Name) && !string.IsNullOrEmpty(x.Phone) &&!string.IsNullOrEmpty(x.Birthday));
Solution 2:[2]
Given your reply to Tomas's answer, I came up with the following solution:
public class CustomerValidator : AbstractValidator<Customer>
{
private class CustomerFieldsValidator : AbstractValidator<Customer>
{
public CustomerFieldsValidator()
{
RuleFor(customer => customer.Name).NotEmpty();
RuleFor(customer => customer.Phone).NotEmpty();
RuleFor(customer => customer.Birthday).NotEmpty();
}
}
public CustomerValidator()
{
Include(new CustomerFieldsValidator());
RuleFor(customer => customer)
.Must(IsUnique)
.When(customer => new CustomerFieldsValidator().Validate(customer).IsValid)
.WithMessage("...");
}
}
If CustomerValidator has only two rules (counting nested validator as 1 rule), you can get rid of .When() clause to shorten the code further.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tomas Grosup |
| Solution 2 | KifoPL |
