Implementé el mensaje de errores de validación con ajax con éxito, pero cuando el formulario de entrada anterior es verdadero, el error anterior en ese formulario de entrada no se oculta. ¿Alguien puede ayudarme a ocultar el error anterior si el formulario de entrada es verdadero?
Este es mi código javascript:
$.ajax({ url: `${window.url}/income`, type: "POST", data: { _token: CSRF_TOKEN, detail: arrValues, data_contact_id, total, description, invoice, transaction_date, to_account_id, }, dataType: "JSON", success: function (response) { console.log(response); if (response.status) { Swal.fire({ icon: "success", type: "success", title: response.message, showConfirmButton: true, }).then((result) => { window.location.href = `${window.url}/income`; }); } }, error: function (jqXHR, textStatus, errorThrown) { console.log(jqXHR); let fields = [ "data_contact_id", "invoice", "transaction_date", "to_account_id", "description", ]; fields.map((field) => { $(`#${field}`).removeClass("is-invalid"); $(`.${field}-error`).html(``); }); let errors = jqXHR.responseJSON.errors; $.each(errors, function (key, value) { $(`#${key}`).addClass("is-invalid"); $(`.${key}-error`).append(` <span class="text-danger" style="font-size: 0.8rem"> ${value.map((v) => "<strong>" + v + "</strong><br>")} </span> `); console.log("Field : ", key); }); Swal.fire({ icon: "error", type: "error", title: "Error!", showConfirmButton: true, }); }, });En mi controlador, he devuelto el error de validación json de Validator::make()
if ($validator->fails()) { return response()->json(['errors' => $validator->errors()->all()]); } $.ajax({ beforeSend: function(){ $(".key_of_form").removeClass("is-invalid"); $(".error_of_key").empty(); }, complete: function(){ // Handle the complete event } error : function(){ // Handle the error event } // ...... }); $(`#${key}`) agregar clase key_of_form
$(`.${key}-error`) agregar clase error_of_key
before submit el formulario o beforeSend de enviar ajax, necesita restablecer los mensajes de error como:
$(".key_of_form").removeClass("is-invalid");
$(".error_of_key").empty();