Hadayat Niazi
Hadayat Niazi

Reputation: 2480

display laravel array validation in javascript

Can anyone please tell me how to display the validation error in javascript? I am sending the request with ajax and want to display the errors.

blade code

$('input[id^="facility_name"]').map(function() {
   return this.value;
}).get();

Laravel Validation

 'facility_name.*' => 'required|string|min:3|max:255',

display error from js

$('.facility_name_error').html(data.responseJSON.errors.facility_name);
or 
$('.facility_name_error').html(data.responseJSON.errors.facility_name[0]);

I attached the output of validation so how can I display this message to html

enter image description here

Upvotes: 0

Views: 1226

Answers (2)

N69S
N69S

Reputation: 17216

If your question is how can you access an object attribute with a dot (.) in the name, you can use the array way

data.responseJSON.errors['facility_name.0'][0]

Upvotes: 1

ali
ali

Reputation: 862

you can access the error as the following:

in this example i will append the errors to li item you can do what you want

          $.ajax({
            type: 'POST',
            url: 'your-url',
            data: {your_data},
            success: function (data) {
           }
        }).fail(function (jqXhr) {
            var resp = jqXhr.responseJSON;
            if (jqXhr.status === 422) {
                var errorsHtml = '<ul>';
                $.each(resp.errors, function (key, value) {
                    errorsHtml += '<li>' + value[0] + '</li>';
                });
                errorsHtml += '</ul>';
               
            }
        }).always(function () {
        });

Upvotes: 2

Related Questions