简体   繁体   中英

Show form validation errors using laravel and ajax

I need to output the validation errors in case if the validation fails. But the errors are not being displayed. I have used Laravel for the server side and ajax for sending the HTTP request.

FORM

<form action="#" method="POST" id="frmcontactuspage" class="contact-form">
            {{ csrf_field() }}
            <div class="form-row">
                <label for="">@lang('language.name') *</label>
                <input id="name" type="text" name="name">
                  <span class="text-danger" id="name-error"></span>
            </div>
            <div class="form-row">
                <label for="">@lang('language.address') *</label>
                <input id="address" type="text" name="address">
                <span class="text-danger" id="address-error"></span>
            </div>
            <div class="form-row">
                <label for="">@lang('language.phone') *</label>
                <input id="phoneno" type="text" name="phoneno">
                   <span class="text-danger" id="phone-error"></span>
            </div>
            <div class="form-row">
                <label for="">@lang('language.email') *</label>
                <input id="email" type="email" name="email">
                <span class="text-danger" id="email-error"></span>
            </div>

            <div class="form-row">
                <label for="">@lang('language.subject') *</label>
                <input id="metitle" type="text" name="subject">
                    <span class="text-danger" id="subject-error"></span>
            </div>
            <div class="form-row">
                <label for="">@lang('language.message') *</label>
                <textarea name="message" id="message" rows="3"></textarea>

            </div>
            <div class="form-row-s">
                 <button type="button" class="submit s-btn-a" id="btncontactuspage">@lang('language.submit')</button>
                </button>
            </div>

        </form>

CONTROLLER

public function insertfeedback(Request $request){
        $validator = Validator::make($request->all(), [
            'name'              => 'required|min:2',
            'email'             => 'required|email',
            'phoneno'           => 'required',
            'address'           => 'required|min:5',
            'message'           => 'required|min:10',
        ]);

    if ($validator->passes()) {
        $contact = new AdminContact;
        $contact->name = $request->name;
        $contact->email = $request->email;
        $contact->address = $request->address;
        $contact->phoneno = $request->phoneno;
        $contact->message = $request->message;
        $contact->inserted_date = date('Y-m-d H:i:s');

        $contact->save();

         $message = "We've received your feedback. Thank You !!!";

        return response()->json(['error' => false, 'message' => $message]);
    }
else{
    return response()->json(['error' => true,'errors' => $validator->errors()]);
}
}

AJAX

$('#btncontactuspage').click(function(event) {
    var formdata = $("#frmcontactuspage").serialize();
    $("#name-error").html("");
    $("#email-error").html("");
    $("#phoneno-error").html("");
    $("#address-error").html("");
    $("#message-error").html("");
    $("#statuspage-msg").html("");
    $.ajax({
        url: baseurl+'/'+locale+'/insertfeedback',
        type: "POST",
        data: formdata
    }).always(function(resp) {
        console.log(resp)
        if(resp.error=='true'){
            if(resp.errors.branch_id){
              $('#branch_id-error').html(resp.errors.branch_id[0]);
            }
            if(resp.errors.name){
              $('#name-error').html(resp.errors.name[0]);
            }
            if(resp.errors.email){
              $('#email-error').html(resp.errors.email[0]);
            }
            if(resp.errors.phoneno){
              $('#phoneno-error').html(resp.errors.phoneno[0]);
            }
            if(resp.errors.address){
              $('#address-error').html(resp.errors.address[0]);
            }
            if(resp.errors.message){
              $('#message-error').html(resp.errors.message[0]);
            }
        }
        if(resp.error=='false'){
            $("#frmcontactuspage")[0].reset();
            $("#statuspage-msg").removeClass('d-none');
            $("#statuspage-msg").html(resp.message);
        }
    });

});

Whats the issue here? Why is the validation not being displayed? Is there any problem in the ajax code? I am not being able to sort it out. help

Try your code as below. use ->fails() method to check validation failed.

if ($validator->fails()) {
    $arr = response()->json(['error' => true,'errors' => $validator->errors()->first()]);
} else {
    $contact = new AdminContact;
    ...
    ...
}

Make sure you pass a Accept: application/json header with your request, otherwise the response will be a 302 redirect and you won't see the validation errors. You need to pass the folliwing in your ajax call:

$.ajax({
    ...
    headers: {
       "Accept": "application/json",
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM