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

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

问题描述

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

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

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

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?

推荐答案

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

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

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

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

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