admin管理员组文章数量:1426223
In HTML5, when you call checkValidity
method or submit the form, the browser evaluates the fields and if a field is invalid it raises the invalid
event.
My question is, can I catch this event and cancel it so that the browser thinks this field as valid. I have tried the following:
<asp:TextBox ID="Line2TextBox" runat="server" placeholder="e.g. Street 9" required oninvalid="return Line2TextBox_Invalid(this);" ></asp:TextBox>
function Line2TextBox_Invalid(obj) {
obj.setCustomValidity('');
return false;
}
When I try to submit the form, it stays invalid.
In HTML5, when you call checkValidity
method or submit the form, the browser evaluates the fields and if a field is invalid it raises the invalid
event.
My question is, can I catch this event and cancel it so that the browser thinks this field as valid. I have tried the following:
<asp:TextBox ID="Line2TextBox" runat="server" placeholder="e.g. Street 9" required oninvalid="return Line2TextBox_Invalid(this);" ></asp:TextBox>
function Line2TextBox_Invalid(obj) {
obj.setCustomValidity('');
return false;
}
When I try to submit the form, it stays invalid.
Share Improve this question asked Mar 5, 2014 at 13:26 sh_kamalhsh_kamalh 3,9014 gold badges41 silver badges50 bronze badges 1-
1.
What do you mean by "so that the browser thinks this field as valid"?2.
How is the validity being checked already? – Paul S. Commented Mar 5, 2014 at 13:42
2 Answers
Reset to default 4You can prevent the browser asking for valid input by calling e.preventDefault();
on the invalid Event. This will just stop the browser's UI popup stating the input is required or must match a pattern, and will not enable the submission of the form.
foo.addEventListener('invalid', function (e) {
e.preventDefault(); // stop it's effects here
e.stopPropagation(); // stop it from bubbling up
});
I made it easier to see the difference on this demo where input A will still be :invalid
, but won't bug you about it in the same way as the normal input B.
If any field is :invalid
, it will prevent submission even if you cancel the invalid Event.
You can't do this, because as soon as the user submits the form the validity is being evaluated. Only then the hooks onsubmit
and oninvalid
are called (i.e. at this time the validity you're trying to set has already been evaluated). Please read this to see how you can use the onchange
-event to acplish what I think you're trying to do.
本文标签: javascriptHow to Cancel invalid Event in HTML5Stack Overflow
版权声明:本文标题:javascript - How to Cancel invalid Event in HTML5 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745470175a2659712.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论