Reputation: 3210
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.
Upvotes: 9
Views: 11265
Reputation: 4299
public static string RemoveWhitespace(this string input)
{
return new string(input.ToCharArray()
.Where(c => !Char.IsWhiteSpace(c))
.ToArray());
}
RuleFor(x => x.Username).Must(s => s.Length == s.RemoveWhitespace().Length);
Upvotes: 0
Reputation: 4263
This worked for me with FluentValidation.MVC5 6.4.0
RuleFor(x => x.username).Must(u => !u.Any(x => Char.IsWhiteSpace(x)));
Upvotes: 3
Reputation:
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");
Upvotes: 3
Reputation:
Try this:
RuleFor(m => m.UserName).NotEmpty().Length(3, 15).Must (u => !string.IsNullOrWhiteSpace(u));
Upvotes: 2
Reputation: 1125
Try the char.IsWhiteSpace
RuleFor(m => m.UserName).NotEmpty().Length(3, 15).Must(userName => !userName.All(c => char.IsWhiteSpace(c)))
Upvotes: 3