在Yii 2中验证内联验证器中的多个属性

Bre*_*ett 3 php yii yii2

我知道你可以使用内联验证器验证单个属性,例如:

['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".');
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我如何将多个属性传递给验证器?...或者我应该$this在验证器中引用它们吗?

top*_*her 8

而不是直接访问额外的字段,例如使用$this->email你可以将其他属性作为字段传递params,就像compareValidator工作方式一样

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


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