【问题标题】:How do I restrict "+ - e , ." from HTML number input?如何限制“+ - e , .”从 HTML 数字输入?
【发布时间】:2017-06-02 13:21:39
【问题描述】:

我有一个 HTML 数字输入元素:<input type="number">。 问题是我还可以输入以下字符:+ - e E , .,我不希望用户能够写。

如何限制这些?

【问题讨论】:

标签: html validation input


【解决方案1】:

编辑:Boris K 得到了更好的答案。

原答案:

这将是实现这一目标的一种方式:

var ageInput = document.getElementById("age")

ageInput.addEventListener("keydown", function(e) {
  // prevent: "e", "=", ",", "-", "."
  if ([69, 187, 188, 189, 190].includes(e.keyCode)) {
    e.preventDefault();
  }
})
<input type="number" id="age">

【讨论】:

  • 以下JSFiddle 为我做了(在我的应用程序中工作)。我改变了很多,但你的回答给了我线索。谢谢
  • @Wulthan,这个小提琴也会限制backspace
  • 完美!最好的一个
  • 但是,这不适用于“粘贴”,对吧?有没有办法将键组合起来并粘贴在一起?
【解决方案2】:

您不应该只依赖<input type="number">,因为这仅适用于现代浏览器,其行为因浏览器而异。

使用 jQuery 执行额外的检查(使用正则表达式):

$('#my-input').keypress(function() {

    var inputValue = $(this).val();
    var reg = /^\d+$/;

    if (reg.test(inputValue)){
        alert("input value is integer");
    } else {
        alert("input value is not an integer");
    }
});

【讨论】:

  • data 等于 inputValue?
  • '1' === parseInt('1', 10) 为假。
  • 好吧,那你最好使用正则表达式。
  • 我同意这一点。感谢您的补充。我将编辑我接受的答案
【解决方案3】:

要限制这些值,请使用 javascript 捕获 keypress 事件,并阻止输入这些字符。 我们从事件中捕获 keyCode,并通过其 ASCII 代码限制输入以不允许这些字符。

document.getElementById('my-number-input').onkeypress = function(e) {
  if(!e) e = window.event;
  var keyCode = e.keyCode || e.which;
  if(!((keyCode >= 48 && keyCode <= 57) || 
  (keyCode >=96 && keyCode <= 105))) {
    e.preventDefault(); //This stops the character being entered.
  }
}

上面的 IF 语句指出,如果 keycode 不在键盘上的 0-9 范围内(包括数字键盘),则不要将字符添加到输入中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-19
    • 2023-03-04
    • 2011-10-01
    • 1970-01-01
    • 2015-01-31
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多