HTML5:为什么我的“无效”属性让模式失败? [英] HTML5: Why does my "oninvalid" attribute let the pattern fail?
问题描述
这个小的HTML5密码字段完全符合oninvalid属性(模式说:最少6个字符):
This little HTML5 password field works perfectly WITHOUT the oninvalid attribute (the pattern say: minimum 6 characters):
<form>
<input type="password" name="user_password_new" pattern=".{6,}" required />
<input type="submit" name="register" value="Register" />
</form>
查看jsFiddle 这里。
See the jsFiddle here.
但是当我添加一个无效的属性,当用户输入不符合模式时,会发出自定义错误消息,整个字段永远无效,请参阅以下代码:
But when I add an oninvalid attribute that gives out a custom error message when user's input does not fit the pattern, the entire field NEVER becomes valid, see the code here:
<form>
<input type="password" name="user_password_new" pattern=".{6,}" oninvalid="setCustomValidity('Minimum length is 6 characters')" required />
<input type="submit" name="register" value="Register" />
</form>
查看jsFiddle here 。
See the jsFiddle here.
你能发现错误吗?
推荐答案
如果您使用 setCustomValidity()
设置值,则该字段无效。这是设置非零长度字符串导致浏览器将该字段视为无效。为了允许任何其他验证的效果,您必须清除自定义的有效性:
If you set a value with setCustomValidity()
then the field is invalid. That is setting a non-zero length string causes the browser to consider the field invalid. In order to allow for the effects of any other validations you have to clear the custom validity:
<input type="password" name="user_password_new" pattern=".{6,}" required
oninvalid="setCustomValidity('Minimum length is 6 characters')"
oninput="setCustomValidity('')" />
这篇关于HTML5:为什么我的“无效”属性让模式失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!