Mik*_*ski 75
这使用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>Run Code Online (Sandbox Code Playgroud)
Dav*_*ain 31
如果不验证输入值,则无法做到这一点.
输入类型=数字
具有type属性值为"number"的input元素表示用于将元素的值设置为表示数字的字符串的精确控件.
由于它是表示数字的字符串,因此无法确定字符串是否表示数字值.
Permitted属性不允许您验证数字输入控件的值.
在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)Run Code Online (Sandbox Code Playgroud)
<input type="number" min="0" />Run Code Online (Sandbox Code Playgroud)
如果您计划将数据发送到服务器,请确保也验证服务器上的数据.客户端JavaScript无法确保正在发送的数据将是您期望的数据.
小智 6
如果您想确保默认值,即最小值,或任何其他值,这是可行的解决方案。这也阻止清除输入字段。同样的方式,您也可以将其设置为最大值。
<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;">Run Code Online (Sandbox Code Playgroud)