validate form with jquery-validate in ajax

0

Hi, I have the following problem, I have made a save function with PHP and Codeigniter , using AJAX too .. everything works fine, but it turns out that I want to validate my form using jquery-validate before making the AJAX request, for that I already have my validation rules and my code is as follows:

$(document).ready(function() {
	
    $("#form_create").unbind('submit').bind('submit', function() {
        var form = $(this);

        $.ajax({
            url: form.attr('action'),
            type: form.attr('method'),
            data: form.serialize(),
            dataType: 'json',
            success:function(response) {
                if(response.success === true) {
                    $(".messages").html('<div class="alert bg-blue alert-dismissible" role="alert">'+
                      '<strong><span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
                    '</div>').fadeIn().delay(4000).fadeOut('slow');

                    $("#form_create")[0].reset();
            
                } else {
                    
                    $(".messages").html('<div class="alert bg-red alert-dismissible" role="alert">'+
                    '<strong> <span class="glyphicon glyphicon-remove-sign"></span> </strong>'+response.messages+
                    '</div>');
                }
            }
        }); 
        return false;
    });

});

The code works fine .. and saves .. now my question is where to add the following code with my validation rules:

$('#form_create').validate({

            highlight: function (input) {
                $(input).parents('.form-line').addClass('error');
            },
            unhighlight: function (input) {
                $(input).parents('.form-line').removeClass('error');
            },
            errorPlacement: function (error, element) {
                $(element).parents('.form-group').append(error);
            }
});
    
asked by FeRcHo 19.01.2017 в 16:44
source

1 answer

2

The easiest thing is to include the submit in the validation, instead of doing the opposite.

$(document).ready(function(){
    $('#form_create').validate({
        ...     
        submitHandler : function(_form)
          {
            var form = $(_form);
            $.ajax({
               // tu código ajax
            })
            return false;
          }
        ...
    });    
});

The ellipses indicate your validations already created.

    
answered by 19.01.2017 / 17:01
source