简体   繁体   English

获取HTML5号码输入的值

[英]Getting the value of a HTML5 number input

I'm using one of the new HTML5 input types, number : 我正在使用一种新的HTML5输入类型, 编号

<input type="number" />

In Opera, which is the only desktop browser I know of which currently recognises it, it renders it as such: 在Opera中,它是我所知道的当前唯一识别它的桌面浏览器,它呈现如下:

在此输入图像描述

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. 如果用户在字段中键入无效内容,例如:“ abc ”,则myInput.value返回的myInput.value空字符串。 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? 有没有办法获得该领域的真正价值?

The HTML5 draft defines: HTML5草案定义:

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. 值清理算法如下:如果元素的值不是有效的浮点数,则将其设置为空字符串。

Reference 1 参考1

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. 我想你已经使用默认值“0”来确保字段保持不变或输入了无效的东西,因为似乎没有明显的方法来区分这两者。

After reading up validation specs and some testing (in Opera 10.54) I concluded that: 在阅读验证规范和一些测试(在Opera 10.54中)后,我得出结论:

<input id="email" type="email" value="blah">
document.getElementById("email").validity.typeMismatch // True

Doesn't work on <input type="number"> . 不适用于<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. 但是该属性确实存在,但它总是返回False。

Read more 2 阅读更多2

You can also set a custom validation method Reference 3 您还可以设置自定义验证方法参考3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM