vadliator无法运作,并传回200 OK

时间:2019-05-15 03:30:27

标签: laravel laravel-validation

尝试验证它,但似乎没有进行验证并返回200 OK。我不知道这会发生什么。当我调试它时,我仍然找不到它不起作用的原因。

服务等级规则

protected $rules = [
        'username' => 'required|max:20|unique:users',
        'email' => 'required|string|email|max:255|unique:users',
        'password' => 'required',
        // **in Production **
        // 'password' => [
        //     'required',
        //     'min:6',
        //     'regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\X])(?=.*[!$#%]).*$/',
        //     'confirmed'
        // ],
        /**
         * Three of the five rules. 
         * English uppercase characters (A – Z)
         * English lowercase characters (a – z)
         * Base 10 digits (0 – 9)
         * Non-alphanumeric (For example: !, $, #, or %)
         * Unicode characters
         */

        'first_name' => 'required|string|max:255',
        'last_name' => 'required|string|max:255',
        'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:5',
        'role' => 'required',

    ];

验证服务类中的方法

    public function validate($user)
    {
        $validator = Validator::make($user, $this->rules);
        $validator->validate();

    }

在控制器中存储方法

 public function store(Request $request)
    {
        $validate = $this->userService->validate($request->all());

        if ($validate->fails()) {

            return response()->json(['message' => $validate->failed()], 400);
        } else {
            try {
                $user = $this->userService->createUser($request);
                return response()->json($user, 201);
            } catch (Exception $e) {
                return response()->json(['message' => $e->getMessage()], 500);
            }
        }
    }

2 个答案:

答案 0 :(得分:0)

如何在服务类中更改validate()方法,以使其返回某些内容,例如:

public function validate($user)
{
    $validator = Validator::make($user, $this->rules);

    if ($validator->fails()) {
        /* Here you can also return something like 
            return redirect('yourView')
            ->withErrors($validator)
            ->withInput();
        */
        // Or you can simply
        return false;
    }

    return true;
}

然后在控制器中可以像这样检查它:

$validate = $this->userService->validate($request->all());

if ($validate)
{
    // Validation was successfull
} else {
    // Validation was not successfull
}

答案 1 :(得分:0)

您不应在服务类中验证您的请求,而应使用Larvel的Custom Form Request,它允许您仅指定规则,它将处理失败的情况(返回浏览器并设置$errors模板中的变量,或发送适当的JSON响应。

基本上你会拥有

public function store(CreateUserRequest $request)
{
    // if you reach here, validation passed.
    try {
        $user = $this->userService->createUser($request);
        return response()->json($user, 201);
    } catch (Exception $e) {
        return response()->json(['message' => $e->getMessage()], 500);
    }
}