Search code examples
c#regexfluentvalidation

Checking for Whitespace in FluentValidation


I'm using FluentValidation and trying to create a rule that throws error if there is any whitespace in the string, i.e. for a username.

I've reviewed these SOs, but doesn't seem to work, I'm sure my syntax is off just a little?

What is the Regular Expression For "Not Whitespace and Not a hyphen" and What is the Regular Expression For "Not Whitespace and Not a hyphen"

RuleFor(m => m.UserName).NotEmpty().Length(3, 15).Matches(@"/^\S\z/");

or

RuleFor(m => m.UserName).NotEmpty().Length(3, 15).Matches(@"[^\s]");

Neither of these seem to work. Other rules are not empty and between 3 and 15 characters.


Solution

  • Just modifying your original rule a bit
    edit Ok, removing delimiters as suggested.

    RuleFor(m => m.UserName).NotEmpty().Length(3, 15).Matches(@"\A\S+\z");
    

    All it does is force there to be non-whitespace in the whole string from start to finish.

    Alternatively, I guess you could combine them into 1 match as in

    RuleFor(m => m.UserName).Matches(@"\A\S{3,15}\z");