简体   繁体   中英

How to prevent user from entering special character in text field of form?

I am trying to prevent user from entering special character like (!,@,&)

Following code restrict user to enter above character only if it is first character after that it allows user to enter above character.

for example & can not be entered but A& can be entered

$('input#first_name-required').bind('keypress', function(e) {
    console.log( e.which );
    if($('input#first_name-required').val().length == 0){
        var k = e.which;
        var ok = k >= 65 && k <= 90 || // A-Z
            k >= 97 && k <= 122 || // a-z
            k >= 48 && k <= 57 //0-9 ;

        if (!ok){
            e.preventDefault();
        }
    }
}); 
if($('input#first_name-required').val().length == 0)

Just remove this condition and it should work fine.

.val() returns the string inside of the input. .length == 0 practically means "if the string is 0 characters long". You validation only runs when the input is empty, thus only when you type the first character.

You have added if condition. I think you might want to check for length grater than 0

 $('input#first_name-required').bind('keypress', function(e) { var k = e.which; var ok = k >= 65 && k <= 90 || // AZ k >= 97 && k <= 122 || // az k >= 48 && k <= 57 //0-9 ; if (!ok){ e.preventDefault(); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="first_name-required"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM