0

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?

2
  • why have you added - two times? Commented Aug 23, 2014 at 8:08
  • Nope.it is a hyphen and an underscore Commented Aug 23, 2014 at 8:13

2 Answers 2

2

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.@&]+$

Sign up to request clarification or add additional context in comments.

Comments

1

Try this regex:

/^[ A-Za-z0-9-.@&]*$/

REGEX DEMO

If you want to escape hyphen as starting character:

^(?!-)[A-Za-z0-9-.@&]*$

REGEX DEMO

If you want to restrict it from start and end both then try this:

^(?!-)[A-Za-z0-9-.@&]*+(?<!-)$

REGEX DEMO

1 Comment

hyphen should be escaped or in the beginning or ending in the set.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.