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

查看:95
本文介绍了为什么我的“无效"?属性让模式失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个小的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('')" />

这篇关于为什么我的“无效"?属性让模式失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆