2.0.36以上版本 rules支持:
- public $array_attribute = ['first', 'second'];
- public function rules()
- {
- return [
- ['array_attribute', 'each', 'rule' => ['customValidatingMethod']],
- ];
- }
- public function customValidatingMethod($attribute, $params, $validator, $current)
- {
- // $attribute === 'array_attribute' (as before)
- // now: $this->$attribute === ['first', 'second'] (on every iteration)
- // previously:
- // $this->$attribute === 'first' (on first iteration)
- // $this->$attribute === 'second' (on second iteration)
- // use now $current instead
- // $current === 'first' (on first iteration)
- // $current === 'second' (on second iteration)
- }
1、对指定字段,作校验 ,判断是否为数据库中已存在的,如选择分类:
- public function rules()
- {
- return [
- [['category_id'], 'required'],
- [['category_id'], 'setCategory'],
- ['category_id', 'exist', 'targetClass' => Category::className(), 'targetAttribute' => 'id'],
- ];
- }
- public function setCategory($attribute, $params)
- {
- $this->category = Category::find()->where(['id' => $this->$attribute])->select('title')->scalar();
- }
2、自定义检验规则,自定义一个函数,并接收参数,对其返回错误示:
提交以后才会触发验证的
- public function rules()
- {
- return [
- [['phone'], 'checkFilterPhone'],
- ];
- }
- public function checkFilterPhone($attribute,$params){
- if(UserModel::findByUsername($this->phone)){
- $this->addError($attribute, '手机号已被注册');
- }
- }
新版写法:
- public function checkIdNum($attribute,$params,$validator){
- //$num = $this->attribute->params;
- // $this->hasErrors()
- // $this->$attribute
- $validator->addError($this,$attribute, '请输入正确的身份证号!');
- }
提示:打印出Validator::$builtInValidators可以看到被支持的所有validators
去除首尾空白字符
- ['email', 'trim']
- 或
- ['email', 'filter', 'filter' => 'trim']
字段必填
- ['email', 'required']
赋予默认值
- ['age', 'default', 'value' => 18]
字符串长度
- ['email', 'string', 'min' => 3, 'max' => 20]
- 或
- ['email', 'string', 'length' => [3, 20]]
格式类型验证
- // 整数格式
- ['age', 'integer']
- // 浮点数格式
- ['salary', 'double']
- // 数字格式
- ['temperature', 'number']
- // 布尔格式
- ['isAdmin', 'boolean']
- // email格式
- ['email', 'email']
- // 日期格式
- ['birthday', 'date']
- // URL格式
- ['website', 'url', 'defaultScheme' => 'http']
验证码
- ['verificationCode', 'captcha']
值在数据表中是唯一的
- ['email', 'unique', 'targetClass' => '\common\models\Users']
值在数据表中已存在
- ['email', 'exist',
- 'targetClass' => '\common\models\User',
- 'filter' => ['status' => User::STATUS_ACTIVE],
- 'message' => 'There is no user with such email.'],
- [['name'], 'unique','message'=>'{attribute} : {value}已存在'],
检查输入的两个值是否一致
- ['passwordRepeat', 'required'] // 必须要加上这一句
- ['passwordRepeat', 'compare', 'compareAttribute' => 'password', 'operator' => '===']
数值范围检查
- ['age', 'compare', 'compareValue' => 30, 'operator' => '>=']
- ['level', 'in', 'range' => [1, 2, 3]]
使用自定义函数过滤
- ['email', 'filter', 'filter' => function($value) {
- // 在此处标准化输入的email
- return strtolower($value);
- }]
文件上传
- ['textFile', 'file', 'extensions' => ['txt', 'rtf', 'doc'], 'maxSize' => 1024 * 1024 * 1024]
图片上传
- ['avatar', 'image', 'extensions' => ['png', 'jpg'],
- 'minWidth' => 100, 'maxWidth' => 1000,
- 'minHeight' => 100, 'maxHeight' => 1000,
- ]
使用正则表达式
- ['username', 'match', 'pattern' => '/^[a-z]\w*$/i']
- [['title', 'content', 'titlepic'], 'safe']
- [['zcode','is_default','type','phone_area','phone','zcode','phone_ext','mobile'],'match','pattern'=>'/^[0-9]+$/','message' => '{attribute} 必须为数字'],
- ['street', 'string', 'max' => 30],
- ['mobile', 'string', 'max' => 11,'min'=>11,'tooLong'=>'手机号格式为11位的数字'],
- [['phone_ext','phone_area'], 'string', 'max' => 4],
- [['phone'], 'string', 'max' => 10,'min'],
- ['zcode','string','max'=>6],
- //必须填写
- array('email, username, password,agree,verifyPassword,verifyCode', 'required'),
- //检查用户名是否重复
- array('email', 'unique', 'message' => '用户名已占用'),
- //用户输入最大的字符限制
- array('email, username', 'length', 'max' => 64),
- //限制用户最小长度和最大长度
- array('username', 'length', 'max' => 7, 'min' => 2, 'tooLong' => '用户名请输入长度为4-14个字符', 'tooShort' => '用户名请输入长度为2-7个字'),
- //限制密码最小长度和最大长度
- array('password', 'length', 'max' => 22, 'min' => 6, 'tooLong' => '密码请输入长度为6-22位字符', 'tooShort' => '密码请输入长度为6-22位字符'),
- //判断用户输入的是否是邮件
- array('email', 'email', 'message' => '邮箱格式错误'),
- //检查用户输入的密码是否是一样的
- array('verifyPassword', 'compare', 'compareAttribute' => 'password', 'message' => '请再输入确认密码'),
- //检查用户是否同意协议条款
- array('agree', 'required', 'requiredValue' => true, 'message' => '请确认是否同意隐私权协议条款'),
- //判断是否是日期格式
- array('created', 'date', 'format' => 'yyyy/MM/dd/ HH:mm:ss'),
- //判断是否包含输入的字符
- array('superuser', 'in', 'range' => array(0, 1)),
- //正则验证器:
- array('name', 'match', 'pattern' => '/^[a-z0-9\-_]+$/'),
- //数字验证器:
- array('id', 'numerical', 'min' => 1, 'max' => 10, 'integerOnly' => true),
- //类型验证 integer,float,string,array,date,time,datetime
- array('created', 'type', 'datetime'),
- //文件验证:
- array('filename', 'file', 'allowEmpty' => true, 'types' => 'zip, rar, xls, pdf, ppt', 'tooLarge' => '图片不要超过800K'),
- array('url',
- 'file', //定义为file类型
- 'allowEmpty' => true,
- 'types' => 'jpg,png,gif,doc,docx,pdf,xls,xlsx,zip,rar,ppt,pptx', //上传文件的类型
- 'maxSize' => 1024 * 1024 * 10, //上传大小限制,注意不是php.ini中的上传文件大小
- 'tooLarge' => '文件大于10M,上传失败!请上传小于10M的文件!'
- )
保存之前 / 更新之前 / 插入之前 / 更新以后 / 插入以后
Model中可以添加控制指定操作之前先执行一段动作:
- // 在执行save()方法之前(已验证):
- public function beforeSave($insert)
- {
- if(parent::beforeSave($insert))
- {
- if($this->isNewRecord)
- {
- $this->create_time = time();
- $this->publishe_time = time();
- $this->user_id = Yii::$app->user->id;
- $this->user_name = Yii::$app->user->identity->username;
- $this->readed = rand(200,500);
- if(emptyempty($this->abstract)){
- $this->abstract = $this->abstract?$this->abstract:substr(strip_tags($this->context),0,200);
- }
- }
- return true;
- }else{
- return false;
- }
- }
- /**
- * This is invoked after the record is saved.
- */
- public function afterSave($insert, $changedAttributes)
- {
- parent::afterSave($insert, $changedAttributes);
- Tag::updateFrequency($this->_oldTags, $this->tags,strtolower($this->getClassName()));
- }
- public function afterDelete() {
- // delete dependencies
- Yii::$app->db->createCommand("DELETE FROM {{%banner_image}} WHERE banner_id=".$this->cacheId)->execute();
- parent::afterDelete();
- }
- public function afterFind()
- {
- parent::afterFind();
- if ($this->type == 'image' && !empty($this->value)) {
- $this->value = Attachment::findOne($this->value);
- }
- }
- ['titlepic', 'filter', 'filter' => function ($val) {
- return $val['id'];
- }, 'skipOnEmpty' => true],
- //titlepic使用的文件上传,传过来是一段数组,取其中的id为值 ,skipOnEmpty 跳过空值处理
Note: 对于绝大多数验证器而言,若其 yii\base\Validator::skipOnEmpty 属性为默认值 true,则它们不会对空值进行任何处理。也就是当他们的关联特性接收到空值时,相关验证会被直接略过。在 核心验证器 之中,只有 captcha
(验证码),default
(默认值), filter
(滤镜),required
(必填),以及 trim
(去首尾空格),这几个验证器会处理空输入。
核心验证器 / filter(滤镜):
- [
- // trim 掉 "username" 和 "email" 输入
- [['username', 'email'], 'filter', 'filter' => 'trim', 'skipOnArray' => true],
- // 标准化 "phone" 输入
- ['phone', 'filter', 'filter' => function ($value) {
- // 在此处标准化输入的电话号码
- return $value;
- }],
- ]
该验证器并不进行数据验证。而是,给输入值应用一个滤镜, 并在检验过程之后把它赋值回特性变量。
filter
:用于定义滤镜的 PHP 回调函数。可以为全局函数名,匿名函数,或其他。 该函数的样式必须是function ($value) { return $newValue; }
。该属性不能省略,必须设置。skipOnArray
:是否在输入值为数组时跳过滤镜。默认为 false。 请注意如果滤镜不能处理数组输入,你就应该把该属性设为 true。 否则可能会导致 PHP Error 的发生。
技巧:如果你只是想要用 trim 处理下输入值,你可以直接用 trim 验证器的。
Tip: There are many PHP functions that have the signature expected for the
filter
callback. For example to apply type casting (using e.g. intval, boolval, ...) to ensure a specific type for an attribute, you can simply specify the function names of the filter without the need to wrap them in a closure:
['property', 'filter', 'filter' => 'boolval'], ['property', 'filter', 'filter' => 'intval'],
单独view页面中加验证
- <script>
- var NowTime = "<?=date('Y-m-d H:i:s')?>";
- jQuery(document).ready(function () {
- jQuery('#w0').yiiActiveForm([
- {
- "id": "plan-plan_et",
- "name": "plan_et",
- "container": ".field-plan-plan_et",
- "input": "#plan-plan_et",
- "validate": function (attribute, value, messages, deferred, $form) {
- yii.validation.required(value, messages, {"message": "结束时间不能为空。"});
- }
- },
- {
- "id": "plan-plan_bt",
- "name": "plan_bt",
- "container": ".field-plan-plan_bt",
- "input": "#plan-plan_bt",
- "validate": function (attribute, value, messages, deferred, $form) {
- yii.validation.required(value, messages, {"message": "开始时间不能为空。"});
- }
- },
- {
- "id": "plan-plan_et",
- "name": "plan_et",
- "container": ".field-plan-plan_et",
- "input": "#plan-plan_et",
- "validate": function (attribute, value, messages, deferred, $form) {
- var planBt = $("#plan-plan_bt").val();
- yii.validation.compare(value, messages, {
- "operator": ">",
- "type": "string",
- "compareValue": planBt,
- "skipOnEmpty": 1,
- "message": "结束时间 必须大于 开始时间"
- });
- }
- }
- ], []);
- });
- </script>