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

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

WBOY
Release: 2016-06-06 20:06:48
Original
1115 people have browsed it

在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>
Copy after login
Copy after login

回复内容:

在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>
Copy after login
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template