如何在Laravel中使用Ajax验证输入数据

Raj*_*009 4 php ajax laravel laravel-validation laravel-5.6

testAjax函数 里面 PostsController类

public function testAjax(Request $request)
  {
    $name = $request->input('name');
    $validator = Validator::make($request->all(), ['name' => 'required']);

    if ($validator->fails()){
        $errors = $validator->errors();
        echo $errors;
    }
    else{
      echo "welcome ". $name;
    }

  }
Run Code Online (Sandbox Code Playgroud)

里面的web.php文件:

Route::get('/home' , function(){
  return view('ajaxForm');
});

Route::post('/verifydata', 'PostsController@testAjax');
Run Code Online (Sandbox Code Playgroud)

ajaxForm.blade.php:

<script src="{{ asset('public/js/jquery.js') }}"></script>

  <input type="hidden" id="token" value="{{ csrf_token() }}">
  Name<input type="text" name="name" id="name">
  <input type="button" id="submit" class="btn btn-info" value="Submit" />
<script>
  $(document).ready(function(){
      $("#submit").click(function(){
        var name = $("#name").val();
        var token = $("#token").val();
        /**Ajax code**/
        $.ajax({
        type: "post",
        url:"{{URL::to('/verifydata')}}",
        data:{name:name,  _token: token},
        success:function(data){
                //console.log(data);
                $('#success_message').fadeIn().html(data);
            }
          });
          /**Ajax code ends**/    
      });
  });
</script>
Run Code Online (Sandbox Code Playgroud)

因此,当通过输入一些数据单击“提交”按钮时,将输出输出消息(echo“ welcome”。$ name;)。但是,当我单击带有空白文本框的Submit按钮时,它不会从控制器打印错误消息,并且在控制台中引发422(不可处理实体)错误。为什么我的方法在这里是错误的,然后如何打印错误消息。请帮忙。先感谢您。 在此处输入图片说明 在此处输入图片说明

Dex*_*gil 7

您的方法实际上没有错,只是您需要在ajax请求上捕获错误响应,因为Laravel验证失败时,它会引发Error 422 (Unprocessable Entity)带有相应错误消息的错误消息。

/**Ajax code**/
$.ajax({
    type: "post",
    url: "{{ url('/verifydata') }}",
    data: {name: name,  _token: token},
    dataType: 'json',              // let's set the expected response format
    success: function(data){
         //console.log(data);
         $('#success_message').fadeIn().html(data.message);
    },
    error: function (err) {
        if (err.status == 422) { // when status code is 422, it's a validation issue
            console.log(err.responseJSON);
            $('#success_message').fadeIn().html(err.responseJSON.message);

            // you can loop through the errors object and show it to the user
            console.warn(err.responseJSON.errors);
            // display errors on each form field
            $.each(err.responseJSON.errors, function (i, error) {
                var el = $(document).find('[name="'+i+'"]');
                el.after($('<span style="color: red;">'+error[0]+'</span>'));
            });
        }
    }
});
/**Ajax code ends**/   
Run Code Online (Sandbox Code Playgroud)

在您的控制器上

public function testAjax(Request $request)
{
    // this will automatically return a 422 error response when request is invalid
    $this->validate($request, ['name' => 'required']);

    // below is executed when request is valid
    $name = $request->name;

    return response()->json([
         'message' => "Welcome $name"
    ]);

  }
Run Code Online (Sandbox Code Playgroud)