jQuery:提交前先进行验证 [英] jQuery: validate before submitting
问题描述
我正在尝试在提交表单之前对其进行验证.我正在尝试使用下面的这段代码,但是它总是提交表单值:
I'm trying to validate my form before submitting it. I'm trying it with this code below, but it always submit the form values:
$('#gestione_profilo').submit(function () {
$("#gestione_profilo").validate({
rules: {
'person_data[document_number]': "required"
},
messages: {
'person_data[document_number]': "required"
}
});
form_data = $(this).serialize();
$.ajax({
url: "<?php echo url_for('profile/index') ?>",
type: "POST",
data: form_data,
success: function() { $("#forma_profile").unmask(); }
});
$("#forma_profile").mask("Aggiornando dati...");
return false;
});
有帮助吗?
致谢
哈维尔
推荐答案
您需要致电 .validate()
在您的document.ready
处理程序中,因为它设置了验证(并且在已经在此处运行的submit
事件上),因此不会运行验证.它应该看起来像这样:
You need to call .validate()
in your document.ready
handler, since it sets up validation (and on a submit
event that's already run here) it doesn't run validation. It should look like this:
$(function() {
$("#gestione_profilo").validate({
rules: {
'person_data[document_number]': "required"
},
messages: {
'person_data[document_number]': "required"
},
submitHandler: function(form){
$.post("<?php echo url_for('profile/index') ?>", $(form).serialize(),
function() {
$("#forma_profile").unmask();
});
$("#forma_profile").mask("Aggiornando dati...");
}
});
});
这涉及在表单本身上添加的否 .submit()
处理程序(.validate()
在下面执行此操作),而是使用 submitHandler
选项仅在表单有效时运行,invalidHandler
是它的对应项,在表单无效时运行.
This involves no .submit()
handler added on the form itself (.validate()
does this underneath), instead use the submitHandler
option which runs only when the form is valid, invalidHandler
is its counterpart, which runs when the form is invalid.
这篇关于jQuery:提交前先进行验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!