大家好,我正在 Laravel 5.5 上工作,我需要为我的 API 显示验证消息,到目前为止我已经这样做了
$validator = Validator::make($request->all(),[
'first_name' => 'email|required',
'last_name' => 'nullable',
'email' => 'email|required',
'mobile_no' => 'nullable|regex:/^[0-9]+$/',
'password' => 'required',
]);
if($validator->fails)
{
$this->setMeta('status', AppConstant::STATUS_FAIL);
$this->setMeta('message', $validator->messages()->first());
return response()->json($this->setResponse(), AppConstant::UNPROCESSABLE_REQUEST);
}
由于 Laravel 5.5 有一些很棒的验证功能,我希望像这样验证我的请求
request()->validate([
'first_name' => 'email|required',
'last_name' => 'nullable',
'email' => 'email|required',
'mobile_no' => 'nullable|regex:/^[0-9]+$/',
'password' => 'required',
]);
但是我在这里遇到问题,我应该怎么做才能检查验证是否失败?就像我通过 if($validator->fails)
最佳答案
在 Laravel 5.5 中,例如 documentation提一下,验证过程非常简单:
- 显示验证错误:
So, what if the incoming request parameters do not pass the given validation rules? As mentioned previously, Laravel will automatically redirect the user back to their previous location. In addition, all of the validation errors will automatically be flashed to the session.
Again, notice that we did not have to explicitly bind the error messages to the view in our GET route. This is because Laravel will check for errors in the session data, and automatically bind them to the view if they are available.
- AJAX 请求和验证:
In this example, we used a traditional form to send data to the application. However, many applications use AJAX requests. When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.
正如您所说:这意味着您不需要将 ifs 用于处理验证,laravel 会自行处理这些问题 :)
关于php - 如何在 Laravel 5.5 中获取验证消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46487040/