如何在通过Ajax提交之前在表单上使用浏览器验证?

时间:2022-12-09 15:14:47

Using an HTML5 form with new type (email, url, etc), I have binded the submit event with a JS function.

使用具有新类型(电子邮件,网址等)的HTML5表单,我已使用JS函数绑定了提交事件。

The problem is that the browser first call this function, and then call its validation system, but only if the submit function hasn't returned false.

问题是浏览器首先调用此函数,然后调用其验证系统,但仅当submit函数未返回false时。

Or, I do the Ajax request and all the work in that function, meaning I always return false.

或者,我执行Ajax请求以及该函数中的所有工作,这意味着我总是返回false。

How could I enable the browser validation to be executed before the call of the submit js function ?

如何在调用submit js函数之前启用浏览器验证?

Thanks for your help.

谢谢你的帮助。

1 个解决方案

#1


5  

From specification the browser should first validate the form and then, if the form is valid should trigger a submit event. This means, that you simply should be able to do your Ajax submit inside the submit event.

根据规范,浏览器应首先验证表单,然后,如果表单有效,则应触发提交事件。这意味着,您应该能够在提交事件中进行Ajax提交。

Currently Opera does first fire the submit event and then does the validation. You can simply call manually the validation inside of your submit listener, using checkValidity-method:

目前Opera首先触发提交事件,然后进行验证。您可以使用checkValidity-method手动调用提交侦听器内部的验证:

$(form).bind('submit', function(){
    if(!this.checkValidity || this.checkValidity()){
        //do ajax and return false
    }
});

Note: that this can doubble the invalid events in those browsers, too. If you don't use them, evrything should be fine. If you want to use them and don't want them doubbled you can use webshims lib, which fixes this and other issues in different browsers.

注意:这也会使这些浏览器中的无效事件变得多一些。如果你不使用它们,evrything应该没问题。如果你想使用它们并且不希望它们加倍,你可以使用webshims lib,它可以修复不同浏览器中的这个问题和其他问题。

#1


5  

From specification the browser should first validate the form and then, if the form is valid should trigger a submit event. This means, that you simply should be able to do your Ajax submit inside the submit event.

根据规范,浏览器应首先验证表单,然后,如果表单有效,则应触发提交事件。这意味着,您应该能够在提交事件中进行Ajax提交。

Currently Opera does first fire the submit event and then does the validation. You can simply call manually the validation inside of your submit listener, using checkValidity-method:

目前Opera首先触发提交事件,然后进行验证。您可以使用checkValidity-method手动调用提交侦听器内部的验证:

$(form).bind('submit', function(){
    if(!this.checkValidity || this.checkValidity()){
        //do ajax and return false
    }
});

Note: that this can doubble the invalid events in those browsers, too. If you don't use them, evrything should be fine. If you want to use them and don't want them doubbled you can use webshims lib, which fixes this and other issues in different browsers.

注意:这也会使这些浏览器中的无效事件变得多一些。如果你不使用它们,evrything应该没问题。如果你想使用它们并且不希望它们加倍,你可以使用webshims lib,它可以修复不同浏览器中的这个问题和其他问题。