验证:满足任何一个规则,而不是所有规则

时间:2014-07-22 10:41:49

标签: laravel laravel-4

我有两个验证规则要应用于'metric_id'字段:

$rules = ['metric_id' => 'exists:metrics,id|in:foo,bar'];

但我不想满足这两个规则,而是要满足另一个(在metrics表中存在或者是指定的值)。

我该怎么做?我是否必须制作自定义验证规则?

1 个答案:

答案 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'];