我有这个 fiddle :
代码只是一个带有模式的数字类型的输入字段
pattern="[0-9]+(\.[0-9]+)?"
如果输入无效,CSS 会添加一个红色边框:
input:invalid { border:1px solid red; }
但是,如果我键入 1.3 然后用 Tab 键退出该字段,我会得到一个红色边框,尽管根据模式这是正确的。这里有什么问题?
PS:这是在 safari 中。
编辑:好的,我添加了 step="any",这似乎解决了这个问题。大家可以确认一下吗?
最佳答案
您已将输入定义为 type=number
。如本文所述,必须使用 step
属性明确允许 float 才能正确验证。
https://blog.isotoma.com/2012/03/html5-input-typenumber-and-decimalsfloats-in-chrome/
在您的输入中添加一个步骤属性:step="any"
:
<input type="number" name="quantity" class="form-control" placeholder="Quantity" tabindex="2" step="any">
此外,根据 MDN pattern
不适用于 number
类型:
This attribute applies when the value of the type attribute is text, search, tel, url or email; otherwise it is ignored
关于CSS 输入 :invalid incorrectly applied,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23107980/