> php教程 > PHP开发 > 본문

yii2.0 모델 규칙 검증에 대한 자세한 설명

黄舟
풀어 주다: 2017-01-03 09:42:56
원래의
1358명이 탐색했습니다.

Yii2에 포함된 등록은 웹사이트의 등록 기능으로 사용할 수 있지만, 반복되는 비밀번호와 인증 코드를 추가하면 더욱 완벽해질 것입니다!

질문:

사용자 이름에는 엄격한 제한이 없습니다. "111", "123456", "_____111"과 같은 사용자 이름은 모두 허용됩니다. 그러면 사용자 입력을 어떻게 제한할 수 있나요? 원하는 사용자 이름은 어떻습니까?

일반 등록에는 비밀번호를 다시 입력하는 입력란이 있습니다. 이는 사용자가 다시 입력한 비밀번호를 확인할 수 있도록 하기 위한 것입니다.

등록된 사용자의 품질을 향상시키고 일괄 등록을 ​​방지하려면 인증 코드를 추가하는 것이 좋습니다.

로직 코드를 수정하지 않고 위의 세 가지 문제를 완벽하게 해결하려면 어떻게 해야 할까요? 아래 튜토리얼을 읽고 나면 한 눈에 이해가 되네요!

고급 버전 2.0.6을 예로 들어 /frontend/models/SignupForm.php를 엽니다

,
            ['username', 'required'],
            ['username', 'unique', 'targetClass' => 'commonmodelsUser', 'message' => 'This username has already been taken.'],
            ['username', 'string', 'min' => 2, 'max' => 255],

            ['email', 'filter', 'filter' => 'trim'],
            ['email', 'required'],
            ['email', 'email'],
            ['email', 'string', 'max' => 255],
            ['email', 'unique', 'targetClass' => 'commonmodelsUser', 'message' => 'This email address has already been taken.'],

            ['password', 'required'],
            ['password', 'string', 'min' => 6],
        ];
    }

只需修改rules规则即可完美实现

a.添加用户字符限制,6-16位

['username', 'string', 'min' => 6, 'max' => 16],

输入限制:用户名由字母,汉字,数字,下划线组成,且不能以数字和下划线开头。

['username', 'match','pattern'=>'/^[(x{4E00}-x{9FA5})a-zA-Z]+[(x{4E00}-x{9FA5})a-zA-Z_d]*$/u',
'message'=>'用户名由字母,汉字,数字,下划线组成,且不能以数字和下划线开头。'],

b.添加重复密码字段

public $repassword;

  一般重复密码与密码的字段验证基本上是一致的,所以可以在password中添加repassword,并添加两次输入一致的限制

[['password','repassword'], 'required'],
[['password','repassword'], 'string', 'min' => 6],
['repassword', 'compare', 'compareAttribute' => 'password','message'=>'两次输入的密码不一致!'],

c.添加验证码字段

public $verifyCode;

  验证码有自带的扩展,只需添加以下代码即可

['verifyCode', 'captcha'],

本例为SiteController中添加[/b]

    public function actions()
    {
        return [
            'captcha' => [
                'class' => 'yiicaptchaCaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }
로그인 후 복사

수정된 규칙

class SignupForm extends Model
{
public $username;
public $email;
public $password;

public $repassword;
public $verifyCode;

public function rules()
{
return [
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['username', 'unique', 'targetClass' => 'commonmodelsUser', 'message' => '该用户名已被使用!'],
['username', 'string', 'min' => 6, 'max' => 16],
['username', 'match','pattern'=>'/^[(x{4E00}-x{9FA5})a-zA-Z]+[(x{4E00}-x{9FA5})a-zA-Z_d]*$/u',
'message'=>'用户名由字母,汉字,数字,下划线组成,且不能以数字和下划线开头。'],

['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'string', 'max' => 255],
['email', 'unique', 'targetClass' => 'commonmodelsUser', 'message' => '该邮箱已经被注册!'],

[['password','repassword'], 'required'],
[['password','repassword'], 'string', 'min' => 6],
['repassword', 'compare', 'compareAttribute' => 'password','message'=>'两次输入的密码不一致!'],

['verifyCode', 'captcha'],
];
}
....
로그인 후 복사

효과 확인

yii2.0 모델 규칙 검증에 대한 자세한 설명

이상은 yii2.0 모델 규칙 검증에 대한 자세한 설명입니다. 더 많은 관련 내용은 PHP 중국어 홈페이지(www.php.cn)를 참고해주세요!


관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 추천
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!