为什么我的“oninvalid"属性让模式失败? [英] 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.
但是当我添加一个 oninvalid 属性时,当用户的输入不符合模式时发出自定义错误消息时,整个字段永远不会变为有效,请参阅此处的代码:
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.
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('')" />
这篇关于为什么我的“oninvalid"属性让模式失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!