在Yii中使用没有参数的验证规则

时间:2014-11-29 07:13:10

标签: php yii yii2

我只是想知道是否有办法从rules方法运行验证函数,而不需要将任何参数传递给它?

通常情况下,您会传入属性的属性名称,但要说您知道要使用的属性,例如$this->foo and $this->bar

因此,正常的自定义内联验证器将如下所示:

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

就像我现在这样做:

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

public function regAvailable($attribute, $params) {

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



}

当然,它完成了这项工作。但是,当我能做的时候,似乎有点矫枉过正:

public function regAvailable($attribute, $params) {

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



}

当然,我仍然可以这样做,但是我觉得那些代码不会非常“干净”,因为那里有那些未使用的参数;我更喜欢这样:

public function regAvailable() {

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



}   

反正有没有做过那样的事情?如果是这样,怎么样?

1 个答案:

答案 0 :(得分:1)

当然你可以做到。您可以避免将任何参数传递给自定义验证方法。例如:

public function regAvailable() {
    if(!$this->hasErrors()){
        if(strlen($this->email) < 10 && $this->email!='info@site.com' && $this->username!='admin'){
              $this->addError('email','Invalid email!');
              $this->addError('username','username must not be admin');
         }
    }
}

但请注意,如果您需要对多个字段执行某些验证,那么使用这些参数会很有用。假设我们需要9个字段来验证主题,如上面的函数。因此,最好使用$attribute参数,因为它引用了验证过程中的字段。