问题
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;
});
Any help?
Regards
Javier
回答1:
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...");
}
});
});
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.
来源:https://stackoverflow.com/questions/4255988/jquery-validate-before-submitting