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?
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']}
}
In Yii2, you should write it like below:
['username', 'customValidator', 'params' => ['extraFields' => 'email']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With