Custom Regular expression in model property ASP.NET MVC4

Arvind897

I need to implement a regular expression validation that allows a-z A-z 0-9 and some special characters _ - . @ &

But should restrict

\ / " : ; * ? " < > { } [ ] ( ) | ! ' % ^ 

tried this pattern but doesn't work.

[Required]
[Display(Name = "User name")]
[RegularExpression("^[-a-zA-Z0-9_-@]*", ErrorMessage = "Invalid characters!")]
public string UserName { get; set; }

Could you please suggest?

Braj

In regex hyphen has a special meaning in Character class that is used to define the range. It should be escaped or put it in the beginning or ending of the set.

Try

[-\w.@&]

Here \w match any word character [a-zA-Z0-9_]

To validate the whole string use ^ and $ to match start and end of the string respectively.

To avoid blank string try + instead of * like ^[-\w.@&]+$

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related