ASP.NET Core Web API - How to specify what a field must contain using Fluent Validation

Viewed 145

Using 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!");
}

How do I validate that NotificationType must have any of the following: SMS or Email or Both?

Thank you

1 Answers

What does NotificationType hold? If you use an enum, you can do:

RuleFor(p => p.NotificationType).NotEmpty();
RuleForEach(p => p.NotificationType).IsInEnum();

This will ensure that the collection isn't empty, and it contains valid enum values.

If you want to ensure that there are no duplicates, considering making NotificationType a HashSet<T>

Related