jQuery: validate before submitting

折月煮酒 提交于 2019-12-13 05:20:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!