Catch a laravel validation exception in ajax

Viewed 180

The api returns the following error. How can I handle the name.0 and name.1 etc in the ajax and display under respective input in the form.

errors: {name.0: ["The name.0 has already been taken."], 
name.1: ["The name.1 has already been taken."]}

ajax:

$.ajax({
    type: "POST",
    url: basePath + "urlHere",
    data: form_data,
    success: function (data) {
        ..... .....
        ..... .....
    },
    error: function (jqXHR, textStatus, errorThrown) {
        var errors = $.parseJSON(jqXHR.responseText);
        console.log('errcheck',  errors.errors['name.0']); //1st input err
        console.log('errLength',  errors.errors.length); //undefined
        if (typeof errors.errors['name.0'] !== 'undefined') { //how to run a loop here?
            $('form#add-form').find('.error-message').each(function () {
                $(this).empty().hide();
            });
            $('form#add-form').find('.error-message').empty()
                .append('<i class="fa fa-info-circle"></i>' + errors.errors['name.0']);
            $('form#add-interest-type-form').find('.error-message').show();
        }
    },
    complete: function () {
        ...... .....
        ..... .....
    }
});

Validation:

$request->validate([
    'group' => 'required',
    'name' => [
        'required', Rule::unique('group_tbl')->where(function ($query) use ($request){
            $query->where('group', $request->get('group')); 
        })
    ]
]);

View:

<input name="group" placeholder="group here" required >
<input name="name[]" placeholder="name here" required >
<small class="error-message" id="title_err" style="display: none;"></small>
<input name="name[]" placeholder="name here" > //added by js but for simplicity added here manually
<small class="error-message" id="title_err" style="display: none;"></small>
1 Answers

You want to use jqXHR.responseJSON instead of jqXHR.responseText.

Implementation example of error callback:

function (jqXHR, textStatus, errorThrown) {
    const data = jqXHR.responseJSON;

    let html = '';

    if (data.errors) {
        const errors = Object.values(data.errors).map(messages => messages[0]);
        html = errors.map(error => `<li>${error}</li>`);
    } else if (data.message) {
        html = `<li>${data.message}</li>`;
    }

    $("#title_err").html(`<ul>${html}</ul>`);
}

Of course, you should change it according to your needs.

BTW: You repeat title_err id twice in your HTML code. You should remove one of them, since id cannot appear more than once in a page.

Related