Best way to restrict a text field to numbers only?

前端 未结 29 1691
长情又很酷
长情又很酷 2020-12-04 22:01

I\'m using the following Javascript to restrict a text field on my website to only accept numerical input, and no other letters or characters. The problem is, it REALLY reje

29条回答
  •  误落风尘
    2020-12-04 22:16

    This is something I made another time for just numbers, it will allow all the formatters as well.

    jQuery

    $('input').keypress(function(e) {
        var a = [];
        var k = e.which;
    
        for (i = 48; i < 58; i++)
            a.push(i);
    
        if (!(a.indexOf(k)>=0))
            e.preventDefault();
    });​
    

    Try it

    http://jsfiddle.net/zpg8k/

    As a note, you'll want to filter on submit/server side as well, for sake of pasting/context menu and browsers that don't support the paste event.

    Edit to elaborate on multiple methods

    I see you're bouncing around the 'accepted' answer, so I'll clear something up. You can really use any of the methods listed here, they all work. What I'd personally do is use mine for live client side filtering, and then on submit and server side use RegEx as suggested by others. However, no client side by itself will be 100% effective as there is nothing stopping me from putting document.getElementById('theInput').value = 'Hey, letters.'; in the console and bypassing any clientside verification (except for polling, but I could just cancel the setInterval from the console as well). Use whichever client side solution you like, but be sure you implement something on submit and server side as well.

    Edit 2 - @Tim Down

    Alright, per the comments I had to adjust two things I didn't think of. First, keypress instead of keydown, which has been updated, but the lack of indexOf in IE (seriously Microsoft!?) breaks the example above as well. Here's an alternative

    $('input').keypress(function(e) {
        var a = [];
        var k = e.which;
    
        for (i = 48; i < 58; i++)
            a.push(i);
    
        if (!($.inArray(k,a)>=0))
            e.preventDefault();
    });​
    

    New jsfiddle: http://jsfiddle.net/umNuB/

提交回复
热议问题