Search code examples
c#.netregexvalidationdata-annotations

.NET RegularExpression DataAnnotation Attribure Not Matching Correctly


I can find plenty of information on Regular Expressions for .NET, but not specifically for the RegularExpression attribute. From what I can see, it behaves differently than normal .NET RegEx.

I am trying to use data annotation validation to validate my product name ViewModel field. The rules are:

  1. No leading or trailing spaces in the string.
  2. Only allow upper and lower case characters and numbers.
  3. No more than a single space between each word.

This is good 123

This is not good

this $%^&* is not good

123 this 555 good

This will be single line since it is a product title.

The regular expression I think I need is [RegularExpression(@"([a-zA-Z0-9]+ ?)+?", ErrorMessage = "The product name can only contain letters, numbers, and a single space between each word")]

But when I start typing a second word, the data annotation says my product name is invalid.

enter image description here

What am I missing? Any help would be appreciated.

Thanks.


Solution

  • Looks like issue is caused by ending ? in @"([a-zA-Z0-9]+ ?)+?" which matches the previous element zero or one time.

    Updating expression to @"([a-zA-Z0-9]+ ?)+" will give result as expected.

    Follow Regular Expression Language - Quick Reference - .NET for more information.