Reputation: 20049
I'm aware you can validate a single attribute using an inline validator such as:
['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 about passing in multiple attributes into the validator? ...or should I just reference them via $this
within the validator?
Upvotes: 3
Views: 2446
Reputation: 14860
Instead of accessing the extra fields directly e.g using $this->email
you could pass the additional attributes as a field in params
, like how the compareValidator
works i.e
['username', 'customValidator', 'params' => ['extraFields' => 'email']]
public function customValidator($attribute, $params) {
//access extrafields using $this->{$params['extraFields']}
}
Upvotes: 8
Reputation: 11068
In Yii2, you should write it like below:
['username', 'customValidator', 'params' => ['extraFields' => 'email']]
Upvotes: 3