Patee Gutee
Patee Gutee

Reputation: 304

FluentValidation with Regular Expression not allowing N/A or NA Ignoring Case and White Space

I use FluentValidation in my ASP.NET MVC app and for some fields to not allow users to enter N/A and its variants.

I found Tim's answer in SO question somewhat helpful but not exactly what I'm looking for. It does work but I don't want to use RegexOptions.IgnoreCase as validation using options like this seems to only happen server-side.

RuleFor(x => x.Question01)
    .Matches(@"^(?!\s*n\s*/?\s*a\s*$).*", RegexOptions.IgnoreCase)
    .WithMessage("Invalid answer.");

I am looking for a pure regex solution (not using RegexOptions.IgnoreCase) ignoring case and white spaces to allow anything except N/A, N / A, NA, N A, n/a, n / a, na, n a, etc.

Upvotes: 0

Views: 1869

Answers (3)

The fourth bird
The fourth bird

Reputation: 163362

If you want to match exactly those values and not allow combinations with upper and lower case mixed, you could list them all using an alternation.

Note that \s also matches a newline.

If you want to allow all except this pattern, you could use a negative lookahead (?! to assert what is on the right is not this pattern and an inline modifier (?i) or (?i:

^(?!(?i:n */? *a)$).+$
  • ^ Start of string
  • (?! Negative lookahead, assert what is on the right is not
    • (?i: Inline modifier for case insensitive match
    • n */? *a match n, optional / surrounded with optional spaces
    • )$ Close inline modifier and assert end of the string
  • ) Close lookahead
  • .+ Match any char 1+ times
  • $ Assert end of the string

.NET regex demo

If this should also work in Javascript, you could use a character class as inline modifiers are not supported.

^(?!(?:[nN] *\/? *[aA])$).+$

Regex demo

Upvotes: 1

Patee Gutee
Patee Gutee

Reputation: 304

This solution does work:

RuleFor(x => x.Question01)
    .Matches(@"^(?!\s*[Nn]\s*/?\s*[Aa]\s*$).*")
    .WithMessage("Invalid answer.");

Upvotes: 2

andyb952
andyb952

Reputation: 2008

This regex will match any variation on N/A, n/a, NA, na

Ignoring all whitespaces between N -> A and N -> / and / -> A

\s*

For case insensitivty

?i:

End Result:

^(?i:n\s*/?\s*a)$

Upvotes: 0

Related Questions