我有一个自定义验证规则is_admin
,用于检查用户是否为管理员。
Laravel是否有"反对"运算符(就像!
在PHP中的工作原理一样),这样我可以执行类似not:is_admin
的操作,这会检查用户是不是管理员:
$rules = array(
'user_id' => 'required|numeric|not:is_admin'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
// return error
}
else
{
// continue
}
感谢。
答案 0 :(得分:0)
是的,您可以通过required_if:field,value
对其进行验证。
您可以在http://laravel.com/docs/5.0/validation#rule-required-if
或者您可以使用not_in:foo,bar
。
您可以在http://laravel.com/docs/5.0/validation#rule-not-in
答案 1 :(得分:0)
是的,我们可以使用规则数组上的条件语句。
$ rules是一个数组,可传递给验证类或在请求类中定义。
示例1:
public function rules{
//here we return an array of rules like shown below.
return [
'field_a' => 'required',
'field_b' => 'required',
];
//we can add any operator by a little change.
save validation rules array in variable like shown below.
$rules = [
'field_a' => 'required',
'field_b' => 'required',
];
//now we can add any rule in $rules array using common ways of writing conditional statements.
//For example field_c is required only when field_a is present and field_b is not
if(isset($this->field_a) && !isset($this->field_b)){
$rules['field_c' => 'required'];
}
//we can apply any kind of conditional statement and add or remove validation rules on the basis of our business logic.
}
示例#2
public function rules(){
$rules = [];
if ($this->attributes->has('some-key')) {
$rules['other-key'] = 'required|unique|etc';
}
if ($this->attributes->get('some-key') == 'some-value') {
$rules['my-key'] = 'in:a,b,c';
}
if ($this->attributes->get('some-key') == 'some-value') {
$this->attributes->set('key', 'value');
}
return $rules;
}