驗證規則
1、內置驗證規則
[['sex', 'partner_id'], 'integer'], [['partner_id', 'camp_id',], 'required'], [['created_at', 'pics'], 'safe'], [['name'], 'string', 'max' => 16],
[['interest', 'quota'], 'number'],
[['path'], 'unique'],
['email', 'email'],
['website', 'url', 'defaultScheme' => 'http']; #說明:CUrlValidator 的別名, 確保了特性是一個有效的路徑.
['username', 'unique', 'targetClass' => '\backend\models\User', 'message' => '用戶名已存在.'],
[['file'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg'],
2、正則驗證規則
//默認值
['status', 'default', 'value' => self::STATUS_ACTIVE],
//區間
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
//正則
['mobile','match','pattern' => '/^1[3456789]{1}\d{9}$/','message'=>'請輸入正確的手機號'],
['name', 'match','not'=>true, 'pattern' => '/^[0-9]+/','message'=>'不能全為數字或以數字開頭'],
3、過濾
['desc', 'filter', 'filter' => function ($value) { if (empty($value)){ return null; } //過濾特殊字符 return Str::purify($value); }],
filter(CFilterValidator )-----過濾驗證方法:
實例:
['name', 'test', 'message'=> '請填寫姓名']
public function test($object, $attributes) {
if($this->name != '張先森') {
$this->addError($object, $attributes['message']);
}
}
//去空格
['username', 'password', 'repassword', 'captcha', 'age', 'sex', 'phone','email'], 'filter', 'filter'=>'trim', 'on'=>'register'],
4、驗證碼
['yzm', 'captcha'],
5、適用場景(自定義場景、或方法)
['shop_id', 'required','on'=>self::SCENARIO_ADMIN_CREATE],
6、比較
['quota', 'compare', 'compareValue' => 9999.99,'type'=>'number', 'operator' => '<='],//
[['discount','payment','pay_method'],'default','value'=>0],
['status', 'compare', 'compareValue' =>$this->oldAttributes['status'],'type'=>'number', 'operator' => '>=','message'=>'狀態不能回撤'],//新修改的狀態必須大於原有的狀態
數值大小
['age', 'compare', 'compareValue' => 30, 'operator' => '>=']; #說明:compareValue(比較常量值) - operator(比較操作符) #說明:CCompareValidator 的別名,確保了特性的值等於另一個特性或常量.
7、時間
['uptime', 'date','format'=>'yyyy-MM-dd', 'timestampAttribute'=>'uptime'],
8,條件唯一(比如同一個班級身份證必須唯一)
['name', 'required', 'message' => '請選擇門店!'], ['shop_id', 'required', 'message' => '請輸入菜品名稱!'], ['name', //只有 name 能接收錯誤提示,數組['name','shop_id']的場合,都接收錯誤提示 'unique', 'targetAttribute'=>['name','shop_id'] , 'targetClass' => '\models\Dishes', // 模型,缺省時默認當前模型。 'comboNotUnique' => '選擇的門店內,該菜品名稱已經存在!' //錯誤信息 ], //自定義函數 ['name', 'check','on'=>['create']],//定義規則,在create場景中對name進行check方法驗證,下面是方法的定義函數 public function check($attribute,$params){ if (empty($this->shop_id)) { return $this->addError($attribute,'請選擇門店!'); } $dish=Dishes::findOne(['name'=>$this->name,'shop_id'=>$this->shop_id]); if($dish){ $this->addError($attribute, '該菜品名稱已存在!'); }else{ $this->clearErrors($attribute); } }
默認值
['updated_at','default','value'=>time(),'on'=>[self::SCENARIO_ADD],'skipOnEmpty'=>false], ['updated_at','editUpdatedAt',on'=>[self::SCENARIO_ADD],'skipOnEmpty'=>false],
參考文章:https://blog.csdn.net/u010010725/article/details/51099326