Alex
Alex

Reputation: 9740

Fluent validation allow empty or value with structure

I have a sort prop that can be empty or values like:

sort=""
sort=["name","desc"]
sort=["name","asc"]


RuleFor(r => r.Sort)
                .NotEmpty()
                .When(nr => nr.Contains("name"))
                .WithMessage("Invalid Sort");

How to allow empty, and non empty with contains a string?

Upvotes: 0

Views: 1102

Answers (1)

Dejan
Dejan

Reputation: 10373

You could just specify a custom rule. Assuming Sort is of string[]:

RuleFor(r => r.Sort)
    .NotNull()
    .Must(x => x.Length == 0 || (x.Length == 2 && x[0] == "name" && 
        (x[1] == "desc" || x[1] == "asc")))
    .WithMessage(...);

And if you need to reuse this logic, just use a custom rule builder as explained here.

Upvotes: 2

Related Questions