'ASP.NET Core Web API - How to validate UserName without whitespace in between, before and after

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:

  1. "Charley Bee"
  2. " CharlerBee"
  3. "Charler Bee "

How do I achieve this?

Thanks



Solution 1:[1]

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

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2