Best way to restrict a text field to numbers only?

前端 未结 29 1637
长情又很酷
长情又很酷 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:35
      document.getElementById('myinput').onkeydown = function(e) {
          if(!((e.keyCode > 95 && e.keyCode < 106)
          || (e.keyCode > 47 && e.keyCode < 58) 
          || e.keyCode == 8
          || e.keyCode == 9)) {
            return false;
          }
      }
    
    0 讨论(0)
  • 2020-12-04 22:37

    shorter way and easy to understand:

    $('#someID').keypress(function(e) { 
        var k = e.which;
        if (k <= 48 || k >= 58) {e.preventDefault()};
    });
    
    0 讨论(0)
  • 2020-12-04 22:38

    Maybe you are using bootstrap. If so, this may suffice:

    <input type="text" data-mask="9999999"> 
    

    Input mask

    0 讨论(0)
  • 2020-12-04 22:39

    I use this:

        oEl.keypress(function(ev)
        {
            var sKey = String.fromCharCode(ev.which);
            if (!sKey.match(/[0-9]/) || !sKey === "") 
                ev.preventDefault();            
        });
    

    The advantage is, that every key which does not provide an input to the field is still allowed, so you don't have to worry about every single special key. Even combos like CTRL + R do still work.

    EDIT As this is not working in Firefox I had to modify the function a little:

        oEl.keypress(function(ev)
        {
            var iKeyCode = ev.which || ev.keyCode;
            var aSpecialKeysForFirefox = [8, 9, 13, 27, 37, 38, 39, 40, 46];
            var sKey = String.fromCharCode(iKeyCode);
            if (sKey !== "" && $.inArray(iKeyCode, aSpecialKeysForFirefox ) < 0 && !sKey.match(/[0-9]/)) {
                ev.preventDefault();
            }
        });
    

    Explanation All Browsers handle jquerys keypress event differently. To make it work in FF the $.inArray check is added. As firefoxs keypress-event doesn't trigger when combinations like strg+tab are used, but the others do, the key.match approach still adds a little value to the latter, as it enables those combinations.

    0 讨论(0)
  • 2020-12-04 22:39

    The following code is something I use extensively. I found the script in a forum, but modified and expanded it to accommodate my needs:

    <script type="text/javascript">
        // Restrict user input in a text field
        // create as many regular expressions here as you need:
        var digitsOnly = /[1234567890]/g;
        var integerOnly = /[0-9\.]/g;
        var alphaOnly = /[A-Za-z]/g;
        var usernameOnly = /[0-9A-Za-z\._-]/g;
    
        function restrictInput(myfield, e, restrictionType, checkdot){
            if (!e) var e = window.event
            if (e.keyCode) code = e.keyCode;
            else if (e.which) code = e.which;
            var character = String.fromCharCode(code);
    
            // if user pressed esc... remove focus from field...
            if (code==27) { this.blur(); return false; }
    
            // ignore if the user presses other keys
            // strange because code: 39 is the down key AND ' key...
            // and DEL also equals .
            if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
                if (character.match(restrictionType)) {
                    if(checkdot == "checkdot"){
                        return !isNaN(myfield.value.toString() + character);
                    } else {
                        return true;
                    }
                } else {
                    return false;
                }
            }
        }
    </script>
    

    Different usage methods would be:

    <!-- To accept only alphabets -->
    <input type="text" onkeypress="return restrictInput(this, event, alphaOnly);">
    <!-- To accept only numbers without dot -->
    <input type="text" onkeypress="return restrictInput(this, event, digitsOnly);">
    <!-- To accept only numbers and dot -->
    <input type="text" onkeypress="return restrictInput(this, event, integerOnly);">
    <!-- To accept only numbers and only one dot -->
    <input type="text" onkeypress="return restrictInput(this, event, integerOnly, 'checkdot');">
    <!-- To accept only characters for a username field -->
    <input type="text" onkeypress="return restrictInput(this, event, usernameOnly);">
    
    0 讨论(0)
提交回复
热议问题