在表单输入类型=“数字”中防止负面输入? [英] Prevent negative inputs in form input type="number"?

查看:166
本文介绍了在表单输入类型=“数字”中防止负面输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想限制用户输入为html格式的正数。



我知道你可以设置min =0,但是可以通过手动输入一个负数来绕过这个。



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

解决方案

不验证输入值是不可能的。


输入类型=数字



值为number的类型属性表示将元素值设置为表示数字的字符串的精确控制。

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

允许的属性不会让您能够验证数字输入控件的值。

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



//选择你的输入element.var numInput = document.querySelector('input' ); //监听numInput.numInput.addEventListener上的输入事件('input',function(){//让我们只匹配数字。 var num = this.value.match(/ ^ \d + $ /); if(num === null){//如果我们没有匹配,值将是空的。 this.value =; }},false)

 < input type =number min =0/>  

在将您的数据发送到服务器时,请确保验证服务器上的数据。
客户端JavaScript无法确保发送的数据将成为您期望的数据。


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

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

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

解决方案

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 string representing a number.

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.

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

// 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.

这篇关于在表单输入类型=“数字”中防止负面输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆