验证规则
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' => 'ackendmodelsUser', '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' => 'modelsDishes', // 模型,缺省时默认当前模型。 '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