Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validation + Submit via $.post

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 com sucesso!' : data);
      top.location.reload();
    }
  );
});

Thanks for the time spent trying to help me! :)

like image 791
silentw Avatar asked Dec 19 '25 05:12

silentw


1 Answers

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

like image 176
Rory McCrossan Avatar answered Dec 21 '25 20:12

Rory McCrossan