'ASP.NET Core Web API - How to perform conditional relative validation using Fluent Validation
In ASP.NET Core-6 Web API, I have this validator using Fluent Validation:
public CustomerValidator()
{
RuleFor(p => p.NotificationType)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty().WithMessage("{PropertyName} should be not empty. NEVER!");
RuleFor(p => p.MobileNumber)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty().WithMessage("{PropertyName} should be not empty. NEVER!");
RuleFor(p => p.Email)
.EmailAddress();
}
I want to validate using these conditions:
If NotificationType = 'Email', then Email should be required
If NotificationType = 'SMS', then MobileNumber should be required
If NotificationType = 'Both', then Email and MobileNumber should be required
How do I achive this?
Thanks
Solution 1:[1]
You can use the When() extension on fluentvalidation.
https://docs.fluentvalidation.net/en/latest/conditions.html
RuleFor(p => p.MobileNumber)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty().WithMessage("{PropertyName} should be not empty. NEVER!")
.When(x => x.NotificationType == "SMS");
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 | Dawood Awan |
