0

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

2 Answers 2

2

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 () {
        });
Sign up to request clarification or add additional context in comments.

Comments

1

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]

2 Comments

thanku for help. Can you please give me an idea how can handle dynamic value facility_name.0 facility_name.1 like this
For that you need to share more details (maybe in another question). Have you took a look to @ali answer? it's a more global way to handle all errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.