Checking multiple attributes inside built-in validator in Yii 2

I know that you can validate a single attribute using the built-in validator , for example:

['country', 'validateCountry']

public function validateCountry($attribute, $params)
{
    if (!in_array($this->$attribute, ['USA', 'Web'])) {
        $this->addError($attribute, 'The country must be either "USA" or "Web".');
    }
}

      

But how do I go to multiple attributes in the validator? ... or should I just reference them via $this

in the validator?

+3


source to share


2 answers


Instead of directly accessing additional fields, for example using $this->email

, you can pass additional attributes as a field in params

for example how it compareValidator

works, i.e.



['username', 'customValidator', 'params' => ['extraFields' => 'email']]


public function customValidator($attribute, $params) {
    //access extrafields using $this->{$params['extraFields']}
}

      

+6


source


In Yii2, you have to write it like below:



['username', 'customValidator', 'params' => ['extraFields' => 'email']]

      

+4


source







All Articles