如何在laravel中使用ajax验证输入数据

时间:2018-03-17 07:55:46

标签: 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;
    }

  }

web.php 文件中

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

Route::post('/verifydata', 'PostsController@testAjax');

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>

因此,当通过输入一些数据点击提交按钮时,输出消息( echo&#34; welcome&#34;。$ name; )正在打印。但是,当我单击带有空文本框的提交按钮时,它不会从控制器打印错误消息,它会在控制台中抛出422(不可处理的实体)错误。为什么我的方法在这里是错误的,如何打印错误消息呢。请帮忙。先感谢您。 enter image description here enter image description here

3 个答案:

答案 0 :(得分:4)

您的方法实际上没有错,只需要在您的ajax请求中捕获错误响应,因为当Laravel验证失败时,它会抛出Error 422 (Unprocessable Entity)并显示相应的错误消息。

/**Ajax code**/
$.ajax({
    type: "post",
    url:"{{URL::to('/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**/   

在您的控制器上

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"
    ]);

  }

答案 1 :(得分:3)

这是一种更好的验证方法:

在您的控制器中:

public function testAjax(Request $request)
{
   $this->validate($request, [ 'name' => 'required' ]);
   return response("welcome ". $request->input('name'));
}

然后,框架将为您创建验证器并验证请求。如果验证失败,它将抛出ValidationException

假设您没有覆盖验证异常的呈现方式,则默认代码the built-in exception handler将会运行

protected function convertValidationExceptionToResponse(ValidationException $e, $request)
{
        if ($e->response) {
            return $e->response;
        }
        $errors = $e->validator->errors()->getMessages();
        if ($request->expectsJson()) {
            return response()->json($errors, 422);
        }
        return redirect()->back()->withInput($request->input())->withErrors($errors);
}

这也是框架为您处理的。

在客户端,您应该可以:

<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);
           },
           error: function (xhr) {
               if (xhr.status == 422) {
                   var errors = JSON.parse(xhr.responseText);
                   if (errors.name) {
                       alert('Name is required'); // and so on
                   }
               }
           }
        });
          /**Ajax code ends**/    
      });
  });
</script>

答案 2 :(得分:0)

在 php 控制器中处理的最佳方式:

        $validator = \Validator::make($request->all(), [
        'footballername' => 'required',
        'club' => 'required',
        'country' => 'required',
    ]);
    
    if ($validator->fails())
    {
        return response()->json(['errors'=>$validator->errors()->all()]);
    }
    return response()->json(['success'=>'Record is successfully added']);