Question

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.

Was it helpful?

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

OTHER TIPS

Try the char.IsWhiteSpace

RuleFor(m => m.UserName).NotEmpty().Length(3, 15).Must(userName => !userName.All(c => char.IsWhiteSpace(c)))

This worked for me with FluentValidation.MVC5 6.4.0

RuleFor(x => x.username).Must(u => !u.Any(x => Char.IsWhiteSpace(x)));

Try this:

RuleFor(m => m.UserName).NotEmpty().Length(3, 15).Must (u => !string.IsNullOrWhiteSpace(u));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top