我有 MyRequest类,其中包含针对请求参数的验证规则。在“文件”字段中,可以为空或字符串或文件。我如何为其建立规则条件?
class MyRequest extends FormRequest
// ...
public function rules()
{
return [
// 'file' => 'image|max:20480', // need to combine this
// 'file' => 'nullable|string', // and this through OR
// 'file' => 'nullable|string|image|max:20480' // <- don't working (string not pass validation)
];
}
}
我也制定了自己的规则:
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Validator::extend('myCustomRule', function ($attribute, $value, $parameters, $validator) {
return !Validator::make([$attribute => $value], ['nullable|image|max:20480'])->fails()
|| !Validator::make([$attribute => $value], ['string'])->fails();
});
}
,但它不起作用。我的想法是,我想使用Laravel规则,而不是编写自己的规则实现来检查字符串长度等。
答案 0 :(得分:0)
我找到了解决方案。它可以正常工作(Laravel v5.4):
class AppServiceProvider extends ServiceProvider
{
// ...
public function boot()
{
Validator::extend('myCustomRule', function ($attribute, $value, $parameters, $validator) {
$validator1 = Validator::make([$attribute => $value], [
'image' => 'nullable|string|max:255'
]);
$validator2 = Validator::make([$attribute => $value], [
'image' => 'image|max:20480'
]);
return !$validator1->fails() || !$validator2->fails();
});
// ...