Reputation: 101
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?
Upvotes: 0
Views: 243
Reputation: 172408
Try this regex:
/^[ A-Za-z0-9-.@&]*$/
If you want to escape hyphen as starting character:
^(?!-)[A-Za-z0-9-.@&]*$
If you want to restrict it from start and end both then try this:
^(?!-)[A-Za-z0-9-.@&]*+(?<!-)$
Upvotes: 1
Reputation: 46841
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.@&]+$
Upvotes: 2