ankur
ankur

Reputation: 4733

Restrict all the special characters through a regex

There is a long set of characters that are not allowed to validate an input box of winform app.

So i figured that rather than making the long list that are not allowed make the shorter one that are allowed.

The set that is allowed are (a-z,A-Z, 0-9,@,.) .Rest every thing that can be entered are not allowed.

This is the regex that i have made for this.

Regex.IsMatch(textBox1.Text, @"[@\.\w]+$")

It seem to work in some cases but when i enter the data in this format normal character or number special character normal character or number it seems to break few example ee(vv, 55)44,aba&3B.

Not able to figure out whats wrong in this.

Upvotes: 1

Views: 6806

Answers (3)

Dmitrii Dovgopolyi
Dmitrii Dovgopolyi

Reputation: 6301

Your regex is not valid, because you don't validate all string, but the last part. You should start it with ^ - beginning of the line symbol.

Regex.IsMatch(textBox1.Text, @"^[\w@.]*$")

\w also means letters in every language, so it will validate the string "абц" too. So if you need only for english, use

Regex.IsMatch(textBox1.Text, @"^[a-zA-Z0-9@.]*$")

Upvotes: 2

Sajin
Sajin

Reputation: 223

Use

^[-a-zA-Z0-9  _  -  \. @]*

as the Regex expression text.

Upvotes: 0

user1711092
user1711092

Reputation:

Try this :

Regex.IsMatch(textBox1.Text, @"^[a-zA-Z0-9@.]*$")

Upvotes: 1

Related Questions