Home > Net >  Regular expression prevent dash from being entered
Regular expression prevent dash from being entered

Time:01-27

I have the following regular expression within my .NET MVC file:

   [RegularExpression(@"[a-zA-Z0-9\-_]{0,10}$", ErrorMessage = "Please
   enter a valid User Code.")]

I want the characters to be no longer than 10 characters. It should allow for alpha-numberic values only and prevent any spaces.

The code above works but the user is able to enter a dash "-". How do I prevent this from happening.

CodePudding user response:

You need to remove the \- from the character class [] and put ^ at the start of the pattern to assert start of string.

@"^[a-zA-Z0-9]{0,10}$"

If you don't want to match an empty string, make it {1,10}.

  •  Tags:  
  • Related