laravel fom表单验证——迹忆客-ag捕鱼王app官网
创建表单请求
除了在laravel 验证入门中提到的一些基本的验证方式之外,我们会遇到更多的更复杂的验证的场景。例如创建一个“表单请求”。form request是包含验证逻辑的自定义请求类。要创建该类,可以使用artisan命令make:request
:
$ php artisan make:request storeblogpost
生成的类将放在app/http/requests
目录中。如果此目录不存在,则在运行make:request
命令时同时创建该目录。下面让我们为rules
方法添加一些验证规则:
/**
* get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
];
}
我们可以在rules方法的签名中键入所需的任何依赖项。它们将通过laravel服务容器自动解析。
那么,如何检查验证规则?我们需要做的就是在控制器方法上输入依赖项。在调用控制器方法之前,将验证传入的表单请求,这意味着我们无需在控制器的方法中写任何的验证逻辑,这将使得我们的控制器变得很简洁:
/**
* store the incoming blog post.
*
* @param storeblogpost $request
* @return response
*/
public function store(storeblogpost $request)
{
// the incoming request is valid...
// retrieve the validated input data...
$validated = $request->validated();
}
如果验证失败,将生成一个跳转到先前的位置的重定向响应。错误也将存储到session中,因此这些信息可以在显示的时候获取到。如果请求是ajax请求,则将向用户返回带有422状态代码的http响应,其中包括验证错误的json表示形式。
在表单请求后添加钩子
如果想在表单请求中添加一个“after”钩子,则可以使用withvalidator
方法。此方法接收完整结构的验证器,使我们可以在实际评估验证规则之前调用其任何方法:
/**
* configure the validator instance.
*
* @param \illuminate\validation\validator $validator
* @return void
*/
public function withvalidator($validator)
{
$validator->after(function ($validator) {
if ($this->somethingelseisinvalid()) {
$validator->errors()->add('field', 'something is wrong with this field!');
}
});
}
授权表单请求
form request 类还包含一个authorize方法。在此方法中,我们可以检查经过身份验证的用户是否实际上具有更新给定资源的权限。例如,我们可以确定用户是否拥有更新博客评论的权限:
/**
* determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
$comment = comment::find($this->route('comment'));
return $comment && $this->user()->can('update', $comment);
}
由于所有表单请求都继承了laravel request基类,因此我们可以使用该类的user
方法访问当前经过身份验证的用户。还要注意在之前的示例中对route方法的调用。通过此方法,我们可以访问在被调用路由上定义的uri参数,例如下面示例中的{comment}
参数:
route::post('comment/{comment}');
如果authorize
方法返回false,则将自动返回带有403状态代码的http响应,并且控制器方法将不会执行。
如果打算在应用程序的另一部分中包含授权逻辑,可以从authorize方法中返回true:
/**
* determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
我们可以在authorize方法的签名中键入所需的任何依赖项。它们将通过laravel服务容器自动解析。
自定义错误消息
我们可以通过重写messages
方法来自定义表单请求所使用的错误消息。此方法应返回属性/规则对及其相应的错误消息的数组:
/**
* get the error messages for the defined validation rules.
*
* @return array
*/
public function messages()
{
return [
'title.required' => 'a title is required',
'body.required' => 'a message is required',
];
}
自定义验证属性
如果希望将验证消息的:attribute
替换为自定义属性名称,则可以通过重写attributes
方法来指定自定义名称。此方法应返回属性/名称对的数组:
/**
* get custom attributes for validator errors.
*
* @return array
*/
public function attributes()
{
return [
'email' => 'email address',
];
}
进行验证之前准备工作
如果在应用验证规则之前需要清理请求中的任何数据,则可以使用prepareforvalidation
方法:
use illuminate\support\str;
/**
* prepare the data for validation.
*
* @return void
*/
protected function prepareforvalidation()
{
$this->merge([
'slug' => str::slug($this->slug),
]);
}