validation of a form through ajax and jquery-validate

0

Good I have the following problem, I made a function to update my data 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:

function editar(id = null) 
{
  if(id) {
    $.ajax({
      url: 'roles/get_datos_id/'+id,
      type: 'post',
      dataType: 'json',
      success:function(response){

        $("#edit_nombre").val(response.Nombre);
        $("#edit_descripcion").val(response.Descripcion);      

        $("#form_edit").unbind('submit').bind('submit', function() {
         
          var form = $(this); 
          
            $.ajax({
              url: form.attr('action') + '/' + id,
              type: 'post',
              data: form.serialize(),
              dataType: 'json',
              success:function(response) {
                if(response.success === true) {
                    $("#modal_editar").modal('hide');
                    alert('se actualizaron los datos');
                    $("#form_edit")[0].reset();
                    tabla_datos.ajax.reload(null, false);  
                  }else{
                    $("#modal_editar").modal('hide');
                    alert('error al actualizar los datos');
              }// /succes
            }); // /ajax
           return false;  
        });       
      }
    });
  }
  else {
    alert('error');
  }
}

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

$('#form_editar').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 24.01.2017 в 15:05
source

1 answer

1

add it in your

$( document ).ready(function() {
});

and then add this in your validate

$( "#form_editar" ).submit(function( event ) {
  event.preventDefault();
  $('#form_editar').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);
        },
        submitHandler: function(form) {
          form.submit();
        }
  });
});
    
answered by 24.01.2017 в 15:36