例如,我有一個處理一些物體創建的 HTTP 請求(讓它成為角色),驗證看起來像這樣:
class CreateRole extends FormRequest
{
public function rules()
{
return [
'name' => 'required|string|max:255',
'permissions' => ['required', 'array'],
...
而且我有一些與名稱或權限列無關的限制。例如,可以創建的最大角色數量。
這樣的自定義驗證可以放在name屬性上,但是看起來不對。
PS:我知道自定義驗證器。問題是放在哪里...
uj5u.com熱心網友回復:
您可以after hook在表單請求中使用CreateRole.php
class CreateRole extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
'title' => ['required', 'string', 'max:255'],
'permissions' => ['required', 'array'],
];
}
/**
* Configure the validator instance.
*
* @param \Illuminate\Validation\Validator $validator
* @return void
*/
public function withValidator($validator)
{
$validator->after(function ($validator) {
if (Role::count() > 10) {
$validator->errors()->add('limit', 'Max number of Roles reached!');
}
});
}
}
uj5u.com熱心網友回復:
您必須創建自定義驗證類,如此Laravel 檔案中所示,并將其放入您的驗證類中,如下所示。
'name' => ['required', 'string', new CustomValidationClass],
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/487051.html
