In my ASP.NET Core-6 Web API, I am using Fluent Validation as shown below:
RuleFor(p => p.UserName)
.NotEmpty().WithMessage("{UserName should be not empty. ERROR!");
I don't want any whitespace, either in between, before and after UserName. That is, I don't want to use any of these:
- "Charley Bee"
- " CharlerBee"
- "Charler Bee "
How do I achieve this?
Thanks
CodePudding user response:
I would use the regex expression to validate space.
\S
: matches any non-whitespace character^
: position at start of a line$
: position at the end of a line
as this regex expression ^[\S] $
RuleFor(m => m.UserName).NotEmpty()
.Matches(@"^[\S] $")
.WithMessage("{UserName should be not empty. ERROR!");
CodePudding user response:
Fluent Validation supports providing rule via predicate by using Must
:
.Must(s => !s.Contains(' '))
RuleFor(m => m.Token)
.Cascade(CascadeMode.Stop) // stop on first failure
.NotEmpty()
.WithMessage("{UserName should be not empty. ERROR!")
.Must(s => !s.Contains(' ')) // or remove Cascade and add nullability check here
.WithMessage("No spaces!");