Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for special characters are not allowed in C#

Tags:

c#

regex

I have to validate a text box from a list of special characters that are not allowed. This all are not allowed characters.

"&";"\";"/";"!";"%";"#";"^";"(";")";"?";"|";"~";"+";" ";
                                                   "{";"}";"*";",";"[";"]";"$";";";":";"=";"

Where semi-column is used to just separate between characters .I tried to write a regex for some characters to validate if it had worked i would extend it.it is not working . What I am doing wrong in this.

Regex.IsMatch(textBox1.Text, @"^[\%\/\\\&\?\,\'\;\:\!\-]+$")
like image 973
ankur Avatar asked Dec 06 '25 09:12

ankur


1 Answers

^[\%\/\\\&\?\,\'\;\:\!\-]+$

matches the strings that consist entirely of special characters. You need to invert the character class to match the strings that do not contain a special character:

^[^\%\/\\\&\?\,\'\;\:\!\-]+$
  ^--- added

Alternatively, you can use this regex to match any string containing only alphanumeric characters, hyphens, underscores and apostrophes.

^[a-zA-Z0-9\-'_]$

The regex you mention in the comments

[^a-zA-Z0-9-'_]

matches a string that contains any character except those that are allowed (you might need to escape the hyphen, though). This works as well, assuming you reverse the condition correctly (accept the strings that do not match).

like image 95
John Dvorak Avatar answered Dec 08 '25 22:12

John Dvorak