↑ Grab this Headline Animator

Friday, January 2, 2009

How to disallow user to enter special charaters in HTML input type text.

Say we have HTML input control with type text for accepting Name from the user.
Here we should not allow special characters to be entered except few characters like (',-).

for doing this in HTML we will create Javascript function which does this and call this function on "onkeypress" event.

function ValidateName(name,e)
// To handle copy paste scenarios
// replace unmaching characters in textbox value with empty
var nameRegex = /^[A-Za-z',.-]{0,50}$/;
while (!name.value.match(nameRegex)) {
name.value = name.value.replace(/[^a-zA-Z,'.-]+/, "");
//FF and IE
e = e || window.event;
var allow = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,'-";
var keycode = e.which || e.keyCode; //For both FF and IE
if (allow.indexOf(String.fromCharCode(keycode)) < 0 && keycode != 13 && keycode != 0)
return false;
return true;

Form allow character string as "abc...zAB..Z,'.-" then checking the typed key (by user), then return false if it not matches with any of the allowed characters.

To handle copy paste scenarios. Write regular expression to allow requered charaters(in my case A-Za-z',.-), then replace unmaching characters in textbox value with empty. Use while loop to remove all umatching group of characters.

calling this function as

<input type="text" name="txtName" id="txtName" onkeypress="return ValidateName(this,event);" onchange="return ValidateName(this,event);" />

Hey one more important thing if user uses mouse to copy and paste name and then clicks on submit button by mouse then onkeypress will not work so better if we also use "onchange" or "onblur" event too, to call the same function.

Submit this story to DotNetKicks

1 comment:

Anonymous said...

the ValidateName is not the opmtimal solution, as it stops you from using the the direction and backspace in any field you apply it on

Post a Comment

Post your comments/questions/feedback for this Article.


Latest Articles