laravel 中 Ajax 数组的验证

Validation for Ajax array in laravel

我正在 posting post 表单中的数据。我想在控制器中验证该数组并向 ajax 调用发送 json 响应。你能帮我一下吗?

这是我提交表单的控制器功能代码。

public function submit()
{

    $data=array(
        'user_firstname'=>$_POST['user_firstname'],
        'user_lastname'=>$_POST['user_lastname'],
        'user_phone'=>$_POST['user_phone'],
        'email'=>$_POST['user_email'],
        'username'=>$_POST['user_username'],
        'password'=>$_POST['user_password'],

    );
     $validation=validator($_POST);
    if($validation->passes()){

      return "Validation passes";

    }
    else{
        return "Validation failed";
    }
}

 protected function validator(array $data)
{
    return Validator::make($data, [
        'user_firstname' => 'required|string|max:255',
        'user_lastname' => 'required|string|max:255',
        'user_phone' => 'required|string|max:15|unique:users',
        'email' => 'required|string|email|max:255|unique:users',
        'username' => 'required|string|max:255|unique:users',
        'password' => 'required|string|min:6|confirmed',
    ]);
}

这是我的 javascript 函数。

 if(currentTab==2)
{

$.ajax({
      url: "register", 
      type: "post",
      headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      },
      data: {'user_firstname':user_firstname,'user_lastname':user_lastname,'user_phone':user_phone,'user_email':user_email,'user_username':user_username,'user_password':user_password},
      success: function(result){
         console.log(result);
        }
    });

}

我想验证数组 return 以下 json 中的所有错误都是我在同一个控制器中的验证器。

如果有其他验证数据的方法,请建议我

验证通过每个测试,即使数组为空

删除您的代码,您可以尝试使用此代码:

public function submit(Request $request)
{
   $error = false; 
   $result = array();
   $responsecode = 200;

   $validator = Validator::make($request, [
            'user_firstname' => 'required|string|max:255',
            'user_lastname' => 'required|string|max:255',
            'user_phone' => 'required|string|max:15|unique:users',
            'email' => 'required|email|unique:users,email',
            'username' => 'required|string|max:255|unique:users,username',
            'password' => 'required|string|min:6|confirmed',
   ]);

   if (!empty($request) && !($validator)){
        try {
            $result = 'Validate!!';     //OR do more your stuff here
        }
        catch(\Exception $e){
            $error = true;
            $responsecode = 500; 
            $result["error_message"] = $e->getMessage();
        }
    } else {
        $error = true;
        $responsecode = 400;
        $result["error_message"] = "";
        if (sizeof($validator->errors()->getMessages()) > 0){
            $messages = $validator->errors()->getMessages();
            foreach ($messages as $key => $value) {
                 $result["error_message"] .= $value[0] .' ';
            }
        }
     }
}

我每次都用过这种格式,试试吧

希望对您有所帮助!!