获取 HTML5 数字输入的值
我正在使用一种新的 HTML5 输入类型 number:
<input type="number" />
在 Opera 中,这是我知道目前唯一能识别它的桌面浏览器,它会将其呈现为:
我的问题我面临的是验证之一。如果用户在字段中输入无效内容,例如:“abc
”,则 myInput.value
返回的值是一个空字符串。这使得无法判断用户是否将该字段留空,或者是否输入了错误的数据。有没有办法获得该领域的真正价值?
I'm using one of the new HTML5 input types, number:
<input type="number" />
In Opera, which is the only desktop browser I know of which currently recognises it, it renders it as such:
The problem I'm facing is one of validation. If a user types something invalid into the field, eg: "abc
", the value returned by myInput.value
is an empty string. This makes it impossible to tell whether the user left the field blank, or if they entered some incorrect data. Is there any way to get the real value of the field?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
HTML5 草案定义:
值清理算法如下:如果元素的值不是有效的浮点数,则将其设置为空字符串。
参考1
我想您应该使用默认值“0”来确保该字段保持不变或者输入了无效的内容,因为似乎没有明显的方法来区分两者。
在阅读了验证规范和一些测试(在 Opera 10.54 中)后,我得出的结论是:
不适用于
。不确定是否应该这样做,或者是否正在进行中。然而该属性确实存在,尽管它总是返回 False。
了解更多2
您还可以设置自定义验证方法参考3
The HTML5 draft defines:
The value sanitization algorithm is as follows: If the value of the element is not a valid floating point number, then set it to the empty string instead.
Reference1
I suppose you'd have use a default value of "0" to make sure the field was left untouched or if something invalid was entered, since there seems to be no obvious way to differentiate the two.
After reading up validation specs and some testing (in Opera 10.54) I concluded that:
Doesn't work on
<input type="number">
. Not sure if it's supposed to, or if it's a work in progress. The property does however exist, though it always returns False.Read more2
You can also set a custom validation method Reference3