Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating multiple attributes within a inline validator in Yii 2

Tags:

php

yii

yii2

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?

like image 525
Brett Avatar asked Nov 26 '25 20:11

Brett


2 Answers

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']}
}
like image 90
topher Avatar answered Nov 28 '25 09:11

topher


In Yii2, you should write it like below:

['username', 'customValidator', 'params' => ['extraFields' => 'email']]
like image 36
Zhang Buzz Avatar answered Nov 28 '25 08:11

Zhang Buzz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!