我有两个验证规则要应用于'metric_id'字段:
$rules = ['metric_id' => 'exists:metrics,id|in:foo,bar'];
但我不想满足这两个规则,而是要满足另一个或(在metrics表中存在或者是指定的值)。
我该怎么做?我是否必须制作自定义验证规则?
答案 0 :(得分:1)
我认为最简单的方法是:
$metric_id_passes =
Validator::make([Input::get('metric_id')], ['metric_id' => 'exists:metrics,id'])->passes()
||
Validator::make([Input::get('metric_id'), ['metric_id' => 'in:foo,bar']])->passes();
或者您可以将其包装在自定义验证规则中:
Validator::extend('MetricIDExistsOrIn', function($attribute, $value, $parameters)
{
return Validator::make(['metric_id' => 'exists:metrics,id'], [ $value ])->passes() ||
Validator::make(['metric_id' => 'in:foo,bar'], [$value])->passes();
});
$rules = ['metric_id' => 'MetricIDExistsOrIn'];