HTML text input allows only numeric input

2018-12-31 00:22发布

Is there a quick way to set an HTML text input (<input type=text />) to only allow numeric keystrokes (plus '.')?

30条回答
妖精总统
2楼-- · 2018-12-31 01:06

JavaScript

function validateNumber(evt) {
    var e = evt || window.event;
    var key = e.keyCode || e.which;

    if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
    // numbers   
    key >= 48 && key <= 57 ||
    // Numeric keypad
    key >= 96 && key <= 105 ||
    // Backspace and Tab and Enter
    key == 8 || key == 9 || key == 13 ||
    // Home and End
    key == 35 || key == 36 ||
    // left and right arrows
    key == 37 || key == 39 ||
    // Del and Ins
    key == 46 || key == 45) {
        // input is VALID
    }
    else {
        // input is INVALID
        e.returnValue = false;
        if (e.preventDefault) e.preventDefault();
    }
}

additional you could add comma, period and minus (,.-)

  // comma, period and minus, . on keypad
  key == 190 || key == 188 || key == 109 || key == 110 ||

HTML

<input type="text" onkeydown="validateNumber(event);"/ >
查看更多
怪性笑人.
3楼-- · 2018-12-31 01:06

You can replace the Shurok function with:

$(".numeric").keypress(function() {
    return (/[0123456789,.]/.test(String.fromCharCode(Event.which) ))
});
查看更多
伤终究还是伤i
4楼-- · 2018-12-31 01:07

Most answers here all have the weakness of using key- events.

Many of the answers would limit your ability to do text selection with keyboard macros, copy+paste and more unwanted behavior, others seem to depend on specific jQuery plugins, which is killing flies with machineguns.

This simple solution seems to work best for me cross platform, regardless of input mechanism (keystroke, copy+paste, rightclick copy+paste, speech-to-text etc.). All text selection keyboard macros would still work, and it would even limit ones ability to set a non-numeric value by script.

function forceNumeric(){
    var $input = $(this);
    $input.val($input.val().replace(/[^\d]+/g,''));
}
$('body').on('propertychange input', 'input[type="number"]', forceNumeric);
查看更多
浪荡孟婆
5楼-- · 2018-12-31 01:07

The best way (allow ALL type of numbers - real negative, real positive, iinteger negative, integer positive) is:

$(input).keypress(function (evt){
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode( key );
    var regex = /[-\d\.]/; // dowolna liczba (+- ,.) :)
    var objRegex = /^-?\d*[\.]?\d*$/;
    var val = $(evt.target).val();
    if(!regex.test(key) || !objRegex.test(val+key) || 
            !theEvent.keyCode == 46 || !theEvent.keyCode == 8) {
        theEvent.returnValue = false;
        if(theEvent.preventDefault) theEvent.preventDefault();
    };
}); 
查看更多
浪荡孟婆
6楼-- · 2018-12-31 01:08

JavaScript

The setInputFilter function from the below script allows you to use any kind of input filter on a text <input>, including various numeric filters. This will correctly handle Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, and all keyboard layouts. Works cross-browser and on mobile, IE 9+. Note that you still must do server side validation!

Try it yourself on JSFiddle.

// Restricts input for the given textbox to the given inputFilter.
function setInputFilter(textbox, inputFilter) {
  ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) {
    textbox.addEventListener(event, function() {
      if (inputFilter(this.value)) {
        this.oldValue = this.value;
        this.oldSelectionStart = this.selectionStart;
        this.oldSelectionEnd = this.selectionEnd;
      } else if (this.hasOwnProperty("oldValue")) {
        this.value = this.oldValue;
        this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
      }
    });
  });
}

Usage:

// Restrict input to digits and '.' by using a regular expression filter.
setInputFilter(document.getElementById("myTextBox"), function(value) {
  return /^\d*\.?\d*$/.test(value);
});

Some regular expressions you might want to use for input filtering:

  • /^-?\d*$/ restricts input to integer numbers
  • /^\d*$/ restricts input to unsigned integer numbers
  • /^[0-9a-f]*$/i restricts input to hexadecimal numbers
  • /^-?\d*[.,]?\d*$/ restricts input to floating point numbers (allowing both . and , as decimal separator)
  • /^-?\d*[.,]?\d{0,2}$/ restricts input to currency values (i.e. at most two decimal places)

You might also want to restrict input to integer values up to a particular limit:

setInputFilter(document.getElementById("myTextBox"), function(value) {
  return /^\d*$/.test(value) && (value === "" || parseInt(value) <= 1500);
});

jQuery

There is also a jQuery version of this. See this answer or try it yourself on JSFiddle.

HTML 5

HTML 5 has a native solution with <input type="number"> (see the specification), but note that browser support varies. As an example, Firefox (as of version 63.0.3) still allows the user to enter text into the field.

Try it yourself on w3schools.com.

More complex validation options

If you want to do some other validation bits and pieces, this could be handy:

查看更多
笑指拈花
7楼-- · 2018-12-31 01:08

So simple....

// In a JavaScript function (can use HTML or PHP).

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

In your form input:

<input type=text name=form_number size=20 maxlength=12 onkeypress='return isNumberKey(event)'>

With input max. (These above allows for a 12-digit number)

查看更多
登录 后发表回答