yii2验证规则

1、内置验证规则

   [['sex', 'partner_id'], 'integer'],
   [['partner_id', 'camp_id',], 'required'],
   [['created_at', 'pics'], 'safe'],
   [['name'], 'string', 'max' => 16],
[['interest', 'quota'], 'number'],
   [['path'], 'unique'],
 ['username', 'unique', 'targetClass' => '\backend\models\User', 'message' => '用户名已存在.'],

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);
            }],

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],
 

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);
    }
}

猜你喜欢

转载自www.cnblogs.com/huay/p/10830456.html