Sunil Kumar Sahoo
Sunil Kumar Sahoo

Reputation: 53687

How to check for special characters using regex

NET. I have created a regex validator to check for special characters means I donot want any special characters in username. The following is the code

Regex objAlphaPattern = new Regex(@"[[email protected]]");
            bool sts = objAlphaPattern.IsMatch(username);

If I provide username as $%^&asghf then the validator gives as invalid data format which is the result I want but If I provide a data [email protected]^&()%^$# then my validator should block the data but my validator allows the data which is wrong

So how to not allow any special characters except a-z A-A 0-9 _ @ .-

Thanks Sunil Kumar Sahoo

Upvotes: 7

Views: 55121

Answers (3)

Fredrik Mörk
Fredrik Mörk

Reputation: 158389

Your pattern checks only if the given string contains any "non-special" character; it does not exclude the unwanted characters. You want to change two things; make it check that the whole string contains only allowed characters, and also make it check for more than one character:

^[[email protected]]+$

Added ^ before the pattern to make it start matching at the beginning of the string. Also added +$ after, + to ensure that there is at least one character in the string, and $ to make sure that the string is matched to the end.

Upvotes: 2

Spencer Ruport
Spencer Ruport

Reputation: 35117

There's a few things wrong with your expression. First you don't have the start string character ^ and end string character $ at the beginning and end of your expression meaning that it only has to find a match somewhere within your string.

Second, you're only looking for one character currently. To force a match of all the characters you'll need to use * Here's what it should be:

Regex objAlphaPattern = new Regex(@"^[[email protected]]*$");
bool sts = objAlphaPattern.IsMatch(username);

Upvotes: 14

Anton Gogolev
Anton Gogolev

Reputation: 115867

Change your regex to ^[[email protected]]+$. Here ^ denotes the beginning of a string, $ is the end of the string.

Upvotes: 1

Related Questions