8

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.

Community
  • 1
  • 1
roadsunknown
  • 3,190
  • 6
  • 30
  • 36

4 Answers4

3

Try the char.IsWhiteSpace

RuleFor(m => m.UserName).NotEmpty().Length(3, 15).Must(userName => !userName.All(c => char.IsWhiteSpace(c)))
Blast_dan
  • 1,135
  • 9
  • 18
  • 1
    Was not able to get this to work. Also might there be a performance if using LINQ to check every character vs. the Regex approach. – roadsunknown Mar 14 '14 at 00:19
3

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");
  • This works, except for the / and \ surrounding the expression. Remove those and either works. If you want to update the answer, I can mark it complete. Thanks! RuleFor(m => m.UserName).NotEmpty().Matches(@"\A\S{3,15}\z"); – roadsunknown Mar 14 '14 at 00:18
  • 1
    `RuleFor(m => m.UserName).NotEmpty().Matches(@"\A\S{3,15}\z"); ` not worked for me. It is showing validating even also when i am entering any characters – Anmol Rathod Jun 29 '18 at 10:04
  • @AnmolRathod - `RuleFor(m => m.UserName).NotEmpty().Matches(@"\A\S{3,15}\z"); not worked for me. It is showing validating even also when i am entering any characters` This -> `\A` is absolute beginning of the string. `\z` is absolute end of string `\S{3,15}` is 3 to 15 _any character except whitespace_. And there you have it .. –  Jul 03 '18 at 19:08
  • @sln what would be final regex than ? – Anmol Rathod Jul 04 '18 at 06:11
  • @AnmolRathod - The final regex was posted March 14, 2014. –  Jul 04 '18 at 16:06
3

This worked for me with FluentValidation.MVC5 6.4.0

RuleFor(x => x.username).Must(u => !u.Any(x => Char.IsWhiteSpace(x)));
Artur Kedzior
  • 3,994
  • 1
  • 36
  • 58
2

Try this:

RuleFor(m => m.UserName).NotEmpty().Length(3, 15).Must (u => !string.IsNullOrWhiteSpace(u));