06 January 2009

Javascript for TextBox Restriction

JavaScript for restricting users from entering unwanted characters in a textbox/ text field.!
One of the easiest way of restricting a user from entering unwanted characters in a text field can be accomplished by using JavaScript functions as below:

<script type="text/javascript" language="javascript">
function keyRestrict(e, validchars)
{
var key='', keychar='';
key = getKeyCode(e);
if (key == null) return true;
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();
validchars = validchars.toLowerCase();
if (validchars.indexOf(keychar) != -1)
return true;
if ( key==null || key==0 || key==8 || key==9 || key==13 || key==27 )
return true;
return false;
}

function getKeyCode(e)
{
if (window.event)
return window.event.keyCode;
else if (e)
return e.which;
else
return null;
}

</script>

After placing the above script in your head section of the web page all you need to do is call the function on the keypress event of a textbox/text field and pass in all the characters that you want to be allowed as follows:

< type="text" name="zip" id="zip" style="width:100px;" maxlength="7" onkeypress="return keyRestrict(event,'1234567890. ')" />>


Note: Please ensure that you conduct server side validations for user input, as JavaScript can be easily disabled in any browser and the above restrictions can be bypassed.

No comments: