Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

html - Why does my "oninvalid" attribute let the pattern fail?

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 ?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...