Brett
Brett

Reputation: 20049

Using a validation rule in Yii with no parameters

I'm just wondering if there is way to run a validation function from your rules method where you don't need to pass in any parameters to it?

So normally you would pass in the attribute name for the property, but say you know what properties you want to use such as $this->foo and $this->bar.

So a normal custom inline validator would be done like this:

['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".');
    }
}

Like I'm currently doing this:

['username', 'regAvailable', 'params' => ['email' => 'email']],

public function regAvailable($attribute, $params) {

    $username = $this->{$attribute};
    $email = $this->{$params['email']};



}

Sure, it does the job. But seems a bit overkill when I can just do:

public function regAvailable($attribute, $params) {

    $username = $this->username;
    $email = $this->email;



}

Sure, I can still do it this way, but then I kinda feel like the code wouldn't be very "clean" by having those unused parameters there; I would prefer to have it like this:

public function regAvailable() {

    $username = $this->username;
    $email = $this->email;



}   

Is there anyway do do something like that? If so, how?

Upvotes: 1

Views: 774

Answers (1)

Ali MasudianPour
Ali MasudianPour

Reputation: 14459

Of course you can do that. You can avoid passing any argument to custom validation method. For example:

public function regAvailable() {
    if(!$this->hasErrors()){
        if(strlen($this->email) < 10 && $this->email!='[email protected]' && $this->username!='admin'){
              $this->addError('email','Invalid email!');
              $this->addError('username','username must not be admin');
         }
    }
}

But, please note that, using those argument would be useful if you need to perform some validation for multiple fields. Assume that we have 9 fields that we need to validate theme like above function. So, it is better to use $attribute argument as it refers to the field which is under validation progress.

Upvotes: 1

Related Questions