HTML5。为什么我的 "oninvalid "属性让模式失败?[英] HTML5: Why does my "oninvalid" attribute let the pattern fail?

本文是小编为大家收集整理的关于HTML5。为什么我的 "oninvalid "属性让模式失败?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

这个小的 HTML5 密码字段在没有 oninvalid 属性(模式说:最少 6 个字符)的情况下完美工作:

<form>
    <input type="password" name="user_password_new" pattern=".{6,}" required />      
    <input type="submit"  name="register" value="Register" />
</form>

查看 jsFiddle 这里.

但是当我添加一个 oninvalid 属性时,当用户的输入不符合模式时会发出自定义错误消息,整个字段永远不会变为有效,请参阅此处的代码:

<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 这里.

你能找出错误吗?

推荐答案

如果用 setCustomValidity() 设置值,则该字段无效.即设置非零长度字符串会导致浏览器认为该字段无效.为了允许任何其他验证的效果,您必须清除自定义有效性:

<input type="password" name="user_password_new" pattern=".{6,}" required
   oninvalid="setCustomValidity('Minimum length is 6 characters')" 
   oninput="setCustomValidity('')" />

本文地址:https://www.itbaoku.cn/post/627527.html

问题描述

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>

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>

See the jsFiddle here.

Can you spot the mistake ?

推荐答案

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('')" />