Remove all special characters from a Textbox using java script

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;

Tarun Juneja

Advertisements

2 thoughts on “Remove all special characters from a Textbox using java script

  1. Hi,
    u r article is good.
    can u forward some more examples on java script , so it will be much helpfull for me to master in it.
    thank u..

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s