Home > Back-end >  ASP.NET Core Web API - How to perform conditional relative validation using Fluent Validation
ASP.NET Core Web API - How to perform conditional relative validation using Fluent Validation

Time:04-29

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

CodePudding user response:

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");
  • Related