简体   繁体   中英

JQuery Validate Text Box value

I'm using jQuery to validate the text box to allow only numbers. The problem is, it allows shift + special characters. I've used the similar code for the name validation except few changes, but it doesn't allow any special characters. I'm confused.My code is

if(e.keyCode==46 || e.keyCode==8|| e.keyCode==9 || e.keyCode==37 || e.keyCode==39)
{
// do nothing allow
}
else if(e.keyCode>=48 && e.keyCode<=57)
{
// do nothing allow
}
else
{
    e.preventDefault();
}

Here is my Fiddle . On the fiddle the first input box didn't allow special characters like @,#,$,% . But the second allows special characters. I checked for the special characters in If statement. Is my logic correct? Is there anything wrong?

This should work:Try

http://jsfiddle.net/cH3zP/6/

var schk=0;
$('#phone').keyup(function(e){
if(e.keyCode==16)
{
    schk=0;
}
});
$('#phone').keydown(function(e){
if(e.keyCode==16)
{
    schk=1;
}
});

What im doing in my code is when user presses down the button i just change the value of global variable schk to 1 .As long as user keep it pressed it will remain 1 .

when user leaves the shift key it is again initialized to 0 allowing its entry.

Why work for 1st input and not for 2nd in Question fiddle?

In your first input box you are not allowing numbers to display. shift+1 fires the same key code as when you press 1.So if you type 1 or ! the key code will be same 49 .

here is the updated code

var reg = new RegExp('^\d+(\.\d{1,2})?$');
$('#phone')
.keydown(function(evt){
    var charCode = evt.which || evt.keyCode;
    var charStr = String.fromCharCode(charCode);
    if (evt.keyCode == 46 || evt.keyCode == 8 || evt.keyCode == 9 || evt.keyCode == 27 || evt.keyCode == 13 ||
        // Allow: Ctrl+A
            (evt.keyCode == 65 && evt.ctrlKey === true) ||
        // Allow: home, end, left, right
            (evt.keyCode >= 35 && evt.keyCode <= 39) || charCode == 46) {
            // let it happen, don't do anything
            return;
        }
        else if (!reg.test(charStr)) {
            evt.preventDefault();
        }
        else {
        }
    });

Hope this helps

I think changing your first event binding function from keydown to keypress solves the problem:

See http://jsfiddle.net/cH3zP/5/

$('#phone').keypress(function(e){
if(e.keyCode==46 || e.keyCode==8|| e.keyCode==9 || e.keyCode==37 || e.keyCode==39)
{
// do nothing allow
}
else if(e.keyCode>=48 && e.keyCode<=57)
{
// do nothing allow
}
else
{
    e.preventDefault();
}
});

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