Home >Backend Development >PHP Tutorial >Yii2 model rules里面自定义规则无效,怎么解决??

Yii2 model rules里面自定义规则无效,怎么解决??

WBOY
WBOYOriginal
2016-06-06 20:06:481116browse

在rules里面自定义规则,代码如下:

<code>public function rules()
    {
        return [
            ['username','required','message'=>'请输入用户名'],
            ['username' , 'checkname' , 'skipOnEmpty' => false],
       ];
}

public function checkname($attribute , $params)
    {
        if(!preg_match("/^[\w]{6,20}$/" , $this->$attribute)){
            $this->addError($attribute , '用户名必须为6~20的数字或字母');
        }
    }</code>

回复内容:

在rules里面自定义规则,代码如下:

<code>public function rules()
    {
        return [
            ['username','required','message'=>'请输入用户名'],
            ['username' , 'checkname' , 'skipOnEmpty' => false],
       ];
}

public function checkname($attribute , $params)
    {
        if(!preg_match("/^[\w]{6,20}$/" , $this->$attribute)){
            $this->addError($attribute , '用户名必须为6~20的数字或字母');
        }
    }</code>

rules方法你在哪里调用的无效?看你贴的code里面也没有调用rules地方啊!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn