Hello!
My problem is the following:
The validation plugin works fine for me, except I don't want the form to submit when it isn't still valid.
The fact is, it validates and displays the errors but it does the submit even if it isn't valid.
Validate
$("form#form-utilizadores").validate({
rules:{
nome:{
required:true
},
utilizador:{
required:true
},
password:{
required:true
},
tipo:{
required:true
}
}
});
Submit
$('form#form-utilizadores').submit(function(e){
e.preventDefault();
var data = $(this).serialize();
$.post('submit/submit-utilizadores.php',data,function(data){
alert((data=='sucesso') ? 'Adicionado sucesso!' : data);
top.location.reload();
}
);
});
Thanks for the time spent trying to help me! :)
Hello!
My problem is the following:
The validation plugin works fine for me, except I don't want the form to submit when it isn't still valid.
The fact is, it validates and displays the errors but it does the submit even if it isn't valid.
Validate
$("form#form-utilizadores").validate({
rules:{
nome:{
required:true
},
utilizador:{
required:true
},
password:{
required:true
},
tipo:{
required:true
}
}
});
Submit
$('form#form-utilizadores').submit(function(e){
e.preventDefault();
var data = $(this).serialize();
$.post('submit/submit-utilizadores.php',data,function(data){
alert((data=='sucesso') ? 'Adicionado sucesso!' : data);
top.location.reload();
}
);
});
Thanks for the time spent trying to help me! :)
Share Improve this question asked May 29, 2012 at 9:26 silentwsilentw 4,8854 gold badges27 silver badges45 bronze badges 1- Do you assign form.submit() before assigning form.validate()? – Salman Arshad Commented May 29, 2012 at 9:49
3 Answers
Reset to default 2You should place the code you have in $('form#form-utilizadores').submit()
and put it in the submitHandler
parameter of the jQuery validate settings, try this:
$("form#form-utilizadores").validate({
rules: {
// your current rules...
},
submitHandler: function(form) {
var data = $(form).serialize();
$.post(
'submit/submit-utilizadores.php',
data,
function(data) {
alert((data=='sucesso') ? 'Adicionado sucesso!' : data);
top.location.reload();
}
);
}
});
The reason your current code is always submitted, is because the form submit
event is always raised, regardless of whether the form is valid or not. Going via the submitHandler
lets jQuery validate control whether to post the form, depending on it's validity.
Try adding this code in your submit handler:
$('form#form-utilizadores').submit(function(e){
e.preventDefault();
if($(this).valid() == false){
return;
}
.
.
.
Return false from submit if your validation fails.