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

javascript - How to Cancel invalid Event in HTML5 - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 4

You 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.

发布评论

评论列表(0)

  1. 暂无评论