Laravel 5.8验证-始终根据任何规则保释

时间:2019-03-18 07:15:59

标签: laravel validation laravel-5 laravel-validation

是否可以将FormRequest规则设置为默认使用bail规则而无需输入规则?

代替:

class StoreRequest extends FormRequest {
    function rules() {
        return [
            'name' => 'bail|required|min:3',
            'last_name' => 'bail|required|min:3',
            'names' => 'bail|required|min:3',
            'email' => 'bail|required|email',
            'type' => 'integer|min:10|max:50',
            // [...]
        ];
    }
}

我想获得更清洁的版本,例如:

class StoreRequest extends FormRequest {

    protected $stopsOnFirstError = true; // I can't find anything like this

    function rules() {
        return [
            'name' => 'required|min:3',
            'last_name' => 'required|min:3',
            'names' => 'required|min:3',
            'email' => 'required|email',
            'type' => 'integer|min:10|max:50',
            // [...]
        ];
    }
}

更新

我的一些规则定义为数组:

'type' => [
    'bail',
    'required',
    'integer',
    Rule::in(ContactType::getValues()),
],

3 个答案:

答案 0 :(得分:2)

1)不用复杂就可以使用字符串替换

<?php
$rules = [
            'name' => 'required|min:3',
            'last_name' => 'required|min:3',
            'names' => 'required|min:3',
            'email' => 'required|email'
        ];
$stopsOnFirstError = true;
if(stopsOnFirstError){
  array_walk($rules, function(&$value, $key) { $value = 'bail|'.$value; } );
}

print_r($rules);
?>

实时演示:Link

输出:

Array
(
    [name] => bail|required|min:3
    [last_name] => bail|required|min:3
    [names] => bail|required|min:3
    [email] => bail|required|email
)

2)您还可以通过其他方式完成此操作,只需添加'*' => 'bail',即可应用于所有字段

class StoreRequest extends FormRequest {
    function rules() {
        return [
            '*' => 'bail',
            'name' => 'required|min:3',
            'last_name' => 'required|min:3',
            'names' => 'required|min:3',
            'email' => 'required|email',
        ];
    }
}

答案 1 :(得分:0)

您始终可以在表单请求类中覆盖svn方法:

validator

答案 2 :(得分:0)

这里我使用的是 Laravel 8 并通过设置 $stopOnFirstFailure = true 轻松停止对第一个错误的验证;

class StoreRequest extends FormRequest{
protected $stopOnFirstFailure = true;

public function rules()
{
    return [
        'name'      => 'required|min:3',
        'last_name' => 'required|min:3',
        'names'     => 'required|min:3',
        'email'     => 'required|email',
    ];
}

}