Best way to restrict a text field to numbers only?

前端 未结 29 1638
长情又很酷
长情又很酷 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:21

    You can do like this to accept only Numbers in text Box,

     function onChange(event){
       var ckeckChars = /[^0-9]/gi;
       if(checkChars.test(event.target.value)) {
            event.target.value = event.target.value.replace(ckeckChars,"");
      }
    
    0 讨论(0)
  • 2020-12-04 22:22

    It's worth pointing out that no matter how tightly you manage to control this via the front end (Javascript, HTML, etc), you still need to validate it at the server, because there's nothing to stop a user from turning off javascript, or even deliberately posting junk to your form to try to hack you.

    My advice: Use the HTML5 markup so that browsers which support it will use it. Also use the JQuery option previously suggested (the inital solution may have flaws, but it seems like the comments have been working through that). And then do server-side validation as well.

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

    I came across your question while trying to figure this out myself. Here is the solution that I came up with.

    // Prevent user from entering non-numeric characters in number boxes.
    (function (inputs) {
        var input;
        var f = function (e) {
            var unicodeRe = /U\+(\d+)/;
            // Chrome doesn't support the standard key property, so use keyIdentifier instead.
            // Instead of the actual character that "key" returns, keyIdentifier returns
            // A string such as "U+004F" representing the unicode character.
    
            // For special characters (e.g., "Shift", a string containing the name of the key is returned.)
            var ch = e.key || e.keyIdentifier;
            var match = ch.match(unicodeRe);
            // keyIdentifier returns a unicode. Convert to string.
            if (match) {
                ch = String.fromCharCode(Number.parseInt(match[1], 16));
            }
            console.log(ch);
            if (ch.length === 1 && /[^0-9]/.test(ch)) {
                if (!/[\b]/.test(ch)) { // Don't prevent backspace.
                    e.preventDefault();
                }
            }
        };
        for (var i = 0, l = inputs.length; i < l; i += 1) {
            input = inputs[i];
            input.onkeydown = f;
        }
    }(document.querySelectorAll("input[type=number],#routeFilterBox")));
    

    Edit: I've discovered that my solution does not allow the user to enter numbers via the numpad in Chrome. The 0-9 keypad keys seem to be returning the character "`" for 0 and A-I for the rest of the number keys.

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

    this will enable the numpad inputs also.

    .keydown(function(event){                                     
        if(event.keyCode == 8 || event.keyCode == 46)             
            return true;                                         
        if(event.keyCode >= 96 && event.keyCode <= 105)           
            return true;                                          
        if(isNaN(parseInt(String.fromCharCode(event.keyCode),10)))
           return false;                                          
    }); 
    
    0 讨论(0)
  • 2020-12-04 22:25

    Add <script type="text/javascript" src="jquery.numeric.js"></script> then use

     $("element").numeric({ decimal: false, negative: false });
    
    0 讨论(0)
  • 2020-12-04 22:27

    Just use regex to get rid of any non number characters whenever a key is pressed or the textbox loses focus.

    var numInput;
    window.onload = function () {   
        numInput = document.getElementById('numonly');
        numInput.onkeydown = numInput.onblur = numInput.onkeyup = function()
        {
            numInput.value = numInput.value.replace(/[^0-9]+/,"");
        }
    }
    
    0 讨论(0)
提交回复
热议问题