在laravel

时间:2018-03-16 08:50:41

标签: ajax laravel laravel-5 laravel-5.2 laravel-5.3

我从表单发布帖子数据。我想在控制器中验证该数组并向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);
        }
    });

}

我想验证数组并返回json中的所有错误以下是我在同一控制器中的验证器。

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

验证即使使用空数组也会通过每个测试

1 个答案:

答案 0 :(得分:1)

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

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] .' ';
            }
        }
     }
}

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

希望这可以帮助你!!