Wai*_*ein 0 laravel laravel-validation laravel-request
我正在使用Laravel开发Web应用程序。我现在正在做的是为验证创建一个FirmRequest。
这是我的FormRequest。
use Illuminate\Foundation\Http\FormRequest;
class StoreVacancy extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'title' => 'required',
'type' => 'required',
'complex_field' => ...need complex conditional validation based on the type field
];
}
}
Run Code Online (Sandbox Code Playgroud)
如果不使用FormRequest,则可以在控制器中创建验证器,并设置复杂的条件验证规则,如下所示。
$v = Validator::make($data, [
//fields and rules
]);
$v->sometimes('reason', 'required|max:500', function ($input) {
return $input->games >= 100;
});
Run Code Online (Sandbox Code Playgroud)
但是问题是我没有在控制器中创建验证器。但是我正在使用FormRequest。如何在FormRequest中实现同一目的?
You can manually adjust the rules depending on the input data:
class StoreVacancy extends FormRequest
{
public function rules()
{
$reason = $this->request->get('reason'); // Get the input value
$rules = [
'title' => 'required',
'type' => 'required',
];
// Check condition to apply proper rules
if ($reason >= 100) {
$rules['complex_field'] = 'required|max:500';
}
return $rules;
}
}
Run Code Online (Sandbox Code Playgroud)
Its not the same as sometimes, but it does the same job.
| 归档时间: |
|
| 查看次数: |
632 次 |
| 最近记录: |