skip to Main Content

I want to validate NID number is exists or not. I want this validation on key up via AJax.
I didn’t work to show errors in ajax before. I write these codes in Jquery. Please help me if I have any mistakes.

in blade

<div class="form-group row">
    <label for="nid" class="col-sm-2 col-form-label">
        NID Number<sup class="text-danger">*</sup>
    </label>
    <div class="col-sm-10">
        <input type="text"
               class="form-control {!! $errors->has('nid_number') ? 'is-invalid' : 'is-valid' !!}"
               placeholder="ভোটার আইডি" id="nid"
               name="nid_number" value="{{ old('nid_number') }}">
        @error('nid_number')
        <span class="invalid-feedback" role="alert">
            <strong>{{ $message }}</strong>
        </span>
        @enderror
    </div>
</div>

jquery cdn

<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>

ajax code

$(document).on('keyup', '#nid', function(){
    $.ajax({
        url:"{{ route('ajax-validation') }}",
        method:'POST',
        data:{query:$(this).val()},
        dataType:'json',
        success:function(data)
        {
            alert(data);
        }
    })
});

in controller

public function ajaxValidation(Request $request)
{
    if ($request->ajax()) {
        $this->validate($request, [
            'nid_number' => 'unique:members',
        ]);
    }
}

I think this validate() returns errors automatically. that’s why I didn’t use any return json_enconde()
Now help me How can I show errors now. Thanks in advance. And sorry for your time.

2

Answers


  1. You can check validation like this :

    public function ajaxValidation(Request $request)
        {
            $validator = Validator::make($request->all(), [
                'nid_number' => 'unique:members',
            ]);
            if ($validator->passes()) {
                return response()->json(['status' => '1']); // success
            }
            return response()->json(['status' => '0'); // not success
        }
    
    Login or Signup to reply.
  2. In your ajax part you are missing error portion

    error:function(data)
    {
       console.log(data);
    }
    

    This is the portion where you will receive laravel validation errors, which will be something like console.log(data.responseJSON.errors) not really sure for this piece of code but you can find in your console. In success method you will never receive validation errors. After that you can play with errors to include in your form inputs

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search