Handy Regular Expressions - Blocking special characters

Blocking special characters in a field is a must in current web environment. If your site allows special characters like "<" "$" and single/double quote then it may be vulnerable to Cross site Scripting and SQL injection attacks.
Here are few regualr expressions, which you can use to block special characters in your text fields.

Blocking all special characters:

The regular extression below allows only alpha numeric characters in a field. So all special characters will be blocked.


Allowing a few required special characters:

There can be a requirement to allow a few characters in your text like hiphen ("-"), spaces. This can be easily done by slightly changing the same regular expression as shown below. Here I have allowed hiphen and spaces in the text.


Similarly you can also allow other characters based on your need. For example to block all special characters except comma (",") you can use this regular expression.


No comments:

Post a Comment

Got something to say? Don't hold it! Tell it to us.

You Might Like