简体   繁体   English

在HTML5数字输入中验证0.5作为步长值

[英]Validate 0.5 as Step Value in HTML5 Number Input

I want to have an input field which only allows to type whole numbers or .5 decimal numbers. 我想要一个输入字段,只允许输入整数或.5十进制数。 eg 0, 0.5, 1, 1.5, 2, 2.5.......etc etc 例如0,0.5,1,1.5,2,2.5 .......等等

I am trying to do this with a HTML5 input field as so 我试图用HTML5输入字段这样做

<input type="number" min="0" max="18" step="0.5" pattern="\\d+" />

but it won't validate the number when it is on a half step of 0.5. 但是当它的步长为0.5时,它不会验证该数字。 It just stays red when clicking outside / validating. 点击外面/验证时它只是保持红色。

Is this possible? 这可能吗? I can't find similar example of how to validate for half steps. 我找不到如何验证半步的类似示例。 DO I need to use jQuery to achieve this? 我需要使用jQuery来实现这一目标吗?

Thanks 谢谢

Fiddle Demo http://jsfiddle.net/b8NrE/906/ 小提琴演示http://jsfiddle.net/b8NrE/906/

Remove the pattern attribute. 删除pattern属性。 This is used for complex validation that requires regular expressions (and your regular expression is only matching sequences of digits). 这用于需要正则表达式的复杂验证(并且您的正则表达式仅匹配数字序列)。 As it is, stipulating min , max , and step already define all the validation that you need: 实际上,规定minmaxstep已经定义了所需的所有验证:

<input type="number" min="0" max="18" step="0.5" />

http://jsfiddle.net/b8NrE/907/ http://jsfiddle.net/b8NrE/907/

您可以尝试:如果步骤不是.5,它将清除文本框

 <input type="number" min="0" oninput="validity.valid||(value='');" step="0.5" /> 

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

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