最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - html setCustomValidity oninvalid and oninput explanation - Stack Overflow

programmeradmin1浏览0评论
<form method="post" action="#">
<input type="text" pattern=".{5,}" name="el" oninvalid="setCustomValidity('Must Be Longer Than 5 Characters')" oninput="setCustomValidity('')"/>
<input type="submit"/>
</form>

so, without the oninput="setCustomValidity('')" part, regardless of the input the form will never be submitted because it will always show the "Must Be Longer Than 5 Characters" error, but by using oninput="setCustomValidity('')" everything works fine, however i don't seem to understand how oninvalid and oninput work together, if i am setting custom validity to '' on input then how is the oninvalid part not overwritten everytime the user presses a key ?
i think this has something to do with how setCustomValidity() Works, no ?

<form method="post" action="#">
<input type="text" pattern=".{5,}" name="el" oninvalid="setCustomValidity('Must Be Longer Than 5 Characters')" oninput="setCustomValidity('')"/>
<input type="submit"/>
</form>

so, without the oninput="setCustomValidity('')" part, regardless of the input the form will never be submitted because it will always show the "Must Be Longer Than 5 Characters" error, but by using oninput="setCustomValidity('')" everything works fine, however i don't seem to understand how oninvalid and oninput work together, if i am setting custom validity to '' on input then how is the oninvalid part not overwritten everytime the user presses a key ?
i think this has something to do with how setCustomValidity() Works, no ?

Share Improve this question asked Sep 15, 2016 at 14:57 macbethmacbeth 1481 silver badge10 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

Enter more than 5 characters and then click on submit, it would work. It will not work only in the cases, where the invalid event is fired at least once.

<form method="post" action="#">
   <input type="text" pattern=".{5,}" name="el"
         oninvalid="setCustomValidity('Must Be Longer Than 5 Characters');"/>
   <input type="submit"/>
</form>

A few basics, reference mdn:
oninvalid is triggered when the constraints are not satisfied.
setCustomValidity method is used to set the result of the validation; an empty string means the constraint is satisfied, and any other string means there is an error.

Reason:
- Once the oninvalid event is trigged you set the result using setCustomValidity to be a non-empty string.
- Now even after(changing the input value) the pattern condition is satisfied, the result of validation is a non-empty string.
- In your code oninvalid="setCustomValidity('...')" oninput="setCustomValidity('')", you clear the result after each input.

发布评论

评论列表(0)

  1. 暂无评论