Remove all special characters from textbox through javascript

Posted: April 7, 2011 in Uncategorized

Sometimes during web page validation we all want to remove all special characters entered by the user. This really easy, you can use client side RegEx library to do same.

This is specially useful when you want avoid all the characters like < >. These can cause scripting attack on your site.

Here are the examples

<input type=”text” value=”this is <script/> tag.” onblur=”validateScriptTags(this)”/>

Here is the validateScriptTags function

function validateScriptTags(sender){
var newValue = sender.value.replace(/[<>]+/g, ”);
sender.value = newValue;

above replaces all < > to empty string. You can replace it to any value just by changing the value in replace function.

similarly if you just want to allow A-Z, a-z, 0-9 only in textbox inputs you can do something like below

var newValue = sender.value.replace(/[^a-zA-Z0-9]+/g, ”);
sender.value = newValue;

  1. Snomi says:

    Thank you, this is very helpful but what if you want “a-z”, “0-9”, and “-” ?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s