1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok thanks. But how would you add it to the rules method so it gets called when validation runs?
@Brett Just ['username', 'regAvailable'] would be sufficient.

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.