Html 防止表单输入类型=“数字”中的负输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31575496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:49:41  来源:igfitidea点击:

Prevent negative inputs in form input type="number"?

htmlformsinputnumbers

提问by Ali

I want to restrict user input to positive numbers in an html form.

我想将用户输入限制为 html 表单中的正数。

I know you can set min="0", however it is possible to bypass this by manually entering a negative number.

我知道您可以设置 min="0",但是可以通过手动输入负数来绕过此设置。

Is there any other way to solve this without writing a validation function?

有没有其他方法可以在不编写验证函数的情况下解决这个问题?

回答by Mikel Rychliski

This uses Javascript, but you don't have to write your own validation routine. Instead just check the validity.validproperty. This will be true if and only if the input falls within the range.

这使用 Javascript,但您不必编写自己的验证例程。而只是检查validity.valid属性。当且仅当输入落在范围内时,这才是真的。

<html>
<body>
<form action="#">
  <input type="number" name="test" min=0 oninput="validity.valid||(value='');"><br>
  <input type="submit" value="Submit">
</form>
</body>
</html>

回答by DavidDomain

This is not possible without validating the value of the input.

如果不验证输入的值,这是不可能的。

input type=number

The input element with a type attribute whose value is "number" represents a precise control for setting the element's value to a stringrepresenting a number.

输入类型=数字

具有值为“数字”的 type 属性的 input 元素表示用于将元素的值设置为表示数字的字符串的精确控件。

Since it is a string representing the number there is no way to be sure that string may be representing numeric values or not.

由于它是一个表示数字的字符串,因此无法确定该字符串是否可以表示数值。

The Permitted attributes will not give you the ability to validate the value of the number input control.

Permitted 属性不会使您能够验证数字输入控件的值。

One way to do this with the help of JavaScript could look like this.

在 JavaScript 的帮助下执行此操作的一种方法可能如下所示。

// Select your input element.
var numInput = document.querySelector('input');

// Listen for input event on numInput.
numInput.addEventListener('input', function(){
    // Let's match only digits.
    var num = this.value.match(/^\d+$/);
    if (num === null) {
        // If we have no match, value will be empty.
        this.value = "";
    }
}, false)
<input type="number" min="0" />

If you are planing on sending your data to a server make sure to validate the data on the server as well. Client side JavaScript can not ensure that the data that is being sent will be what you expect it to be.

如果您计划将数据发送到服务器,请确保同时验证服务器上的数据。客户端 JavaScript 无法确保发送的数据符合您的预期。

回答by user7135197

If you want to ensure default value, i.e min value, or any other value, this is working solution. This is also preventing to clear the input field. Same way you can set to it's max value as well.

如果您想确保默认值,即最小值,或任何其他值,这是可行的解决方案。这也阻止清除输入字段。同样的方式,您也可以将其设置为最大值。

<input type="number" min="1" max="9999" maxlength="4" oninput="this.value=this.value.slice(0,this.maxLength||1/1);this.value=(this.value   < 1) ? (1/1) : this.value;">

回答by user7135197

The following script will only allow numbers or a backspace to be entered into the input.

以下脚本只允许在输入中输入数字或退格。

var number = document.getElementById('number');

number.onkeydown = function(e) {
    if(!((e.keyCode > 95 && e.keyCode < 106)
      || (e.keyCode > 47 && e.keyCode < 58) 
      || e.keyCode == 8)) {
        return false;
    }
}
<input type="number" id="number" min="0">

回答by Hafenkranich

type="number"already solves allowing numbers only to be typed as the other answers here point out.

type="number"已经解决了只允许输入数字,正如这里的其他答案所指出的那样。

Just for reference: with jQuery you can overwrite negative values on focusout with the following code:

仅供参考:使用 jQuery,您可以使用以下代码覆盖 focusout 上的负值:

$(document).ready(function(){
    $("body").delegate('#myInputNumber', 'focusout', function(){
        if($(this).val() < 0){
            $(this).val('0');
        }
    });
});

This does not replace server side validation!

这不会取代服务器端验证!

回答by Majedur Rahaman

In HTML5, I like this way. Also it's much suitable with angular.

在 HTML5 中,我喜欢这种方式。它也非常适合 angular。

<input type="number" min="0" oninput="this.value = Math.abs(this.value)">