Click here to Skip to main content
15,910,471 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have implemented java script validation for "first name" which accepts character only. It's working proper on computer and Iphone but if I a checking It on other mobile It's accept numbers also. What should I do for this problem?
I am using following code
Thanks In Advance
HTML
var alpha = "[ A-Za-z]";
var numeric = "[0-9]"; 
var alphanumeric = "[ A-Za-z0-9]"; 

function onKeyValidate(e,charVal){
    var keynum;
    var keyChars = /[\x00\x08]/;
    var validChars = new RegExp(charVal);
    if(window.event)
    {
        keynum = e.keyCode;
    }
    else if(e.which)
    {
        keynum = e.which;
    }
    var keychar = String.fromCharCode(keynum);
    if (!validChars.test(keychar) && !keyChars.test(keychar))   {
        return false
    } else{
        return keychar;
    }
} 




<input type="text" value="" name="first_name" id="first_name" placeholder="First Name" onkeypress="return onKeyValidate(event,alpha);"/>


What I have tried:

I tried this above code please help me
Posted
Updated 1-Jun-16 13:12pm
Comments
Sergey Alexandrovich Kryukov 1-Jun-16 19:03pm    
No, [A-Za-z] is not "alpha", and "alphanumeric" is not [A-Za-z0-9].
These characters is a narrow subset of Latin characters is used in English, even American English.
JavaScript is very powerful, it allows to classify characters to letters and non-letters in all languages.
As to your code... let me see...

You are using very obsolete JavaScript features, such as window.event, which is just wrong; but yes, some "browsers" (quotation makes intended :-) really worked that way.

The standard requires the use of event.preventDefault(); you are not using it.

—SA

1 solution

Please see my comment to the question.

Please see the API you are missing: Event.preventDefault() — Web APIs | MDN[^].

See also this tutorial: Keyboard Text Input Filtering: Examples[^].

If you want to allow any Unicode letter, not just narrow subset of letters A to Z and a to z, you have to use Unicode Regular Expressions. They are really supported by any non-nonsense JavaScript implementation. Please see: Regex Tutorial — Unicode Characters and Properties[^].

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900