验证规则中的“非”运算符

问题描述 投票:3回答:2

我有一个自定义验证规则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
}

谢谢。

laravel laravel-4 laravel-5
2个回答
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查看更多详情


0
投票

是的,我们可以通过在rules数组上使用条件语句。

$ rules是我们传递给验证类或在Request类中定义的数组。

示例#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;
}
© www.soinside.com 2019 - 2024. All rights reserved.