Home > Software design >  ASP.NET Core Web API - How to validate UserName without whitespace in between, before and after
ASP.NET Core Web API - How to validate UserName without whitespace in between, before and after

Time:05-01

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

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