[[+content_image]]
G
G
Good Samaritan2018-06-11 12:11:18
Yii
Good Samaritan, 2018-06-11 12:11:18

Why is the validation rule not working?

The following code fails validation

public function rules() {
    return[
      [['name','email'],'required'],
      ['email','email'],
      //['name','string','min'=>2,'tooShort'=>'Мало'],
      //['name','string','max'=>5,'tooLong'=>'Много'],
      ['name','string','length'=>[2,5]],
      ['name','myRule'],
      ['text','trim']
    ];
  }

  public function myRule($attr){
    if(!in_array($this->attributes,['hello','world'])){
      $this->addError($attr,'Не в массиве имен');
    }
  }

I enter hello in the name field. Writes what is not in the array of names

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
M
Maxim Fedorov, 2018-06-11
@qonand

does not work because in the validation rule it is necessary to check not the entire array of attributes, but the passed attribute

public function myRule($attr){
    if(!in_array($this->$attr, ['hello', 'world'])){
        $this->addError($attr, 'Не в массиве имен');
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question