3

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?

2
  • I think you do not understand what is happening here. The array ['country', 'validateCountry'] basically states that validateCountry is applied to country, if you want to apply the validator function to other attribute just add ['secondAttribute', 'validateCountry'] and the validator would automatically apply the function for both country and secondAttribute Commented Nov 27, 2014 at 10:46
  • 1
    @Mr.Meshuggah Yes, I understand how it works. It works on the country attribute which is $this->country. However I need to make a custom validator function to check the username and email attributes against the database; I would prefer to pass them BOTH to a single validator rather than separately so I can just run the single query. Commented Nov 27, 2014 at 10:56

2 Answers 2

8

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']}
}
Sign up to request clarification or add additional context in comments.

1 Comment

That worked, but I had to do this: ['username', 'customValidator', 'params' => ['email' => 'email']]
3

In Yii2, you should write it like below:

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

2 Comments

You have only copied the above answer, without any useful explanation.
@L.Antonelli notice the update time. I answered for Yii2 in 2015, and he edited the answer in 2016. It's he who copied my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.