views:

5086

answers:

4

Hi Buddies,

How can i restrict users fro entering special characters in the text box.I want only numbers and alphabets to be entered ( Typed / Pasted ) Any Samples ?

Thanks in advance

A: 

It would help you... assume you have a form with "formname" form and a text box with "txt" name. then you can use following code to allow only aphanumeric values

var checkString = document.formname.txt.value;
if (checkString != "") {
    if ( /[^A-Za-z\d]/.test(checkString)) {
     alert("Please enter only letter and numeric characters");
     document.formname.txt.focus();
     return (false);
    }
}
Green Techy
+1  A: 

You have two approaches to this:

  1. check the "keypress" event. If the user presses a special character key, stop him right there
  2. check the "onblur" event: when the input element loses focus, validate its contents. If the value is invalid, display a discreet warning beside that input box.

I would suggest the second method coz its less irritating.

Additionally, I will also suggest that you reconsider if you really want to prevent users from entering special characters. Because many people have $, #, @ and * in thier passwords.

I presume that this might be in order to prevent SQL injection; if so: its better that you handle the checks server-side. Or better still, escape the values and store them in the database.

cheers, jrh.

Here Be Wolves
Limiting input isn't necessarily restrictive, it might be to input phone numbers, Zip codes, dates, etc.But +1 to the advice to double the checking on server side!
PhiLho
A: 

i need to see the method of special character validation in javascript

jawahar