Yii2.0 常用rules规则汇总

 
更多

yii2 常用 rules 规则汇总。

// 去除首尾空白字符
['email', 'trim'] 或 ['email', 'filter', 'filter' => 'trim']

// 验证字段必填
['email', 'required', 'message' => 'email不能为空']

// 赋予默认值
['age', 'default', 'value' => 20]

// 验证字符串长度
['email', 'string', 'min' => 3, 'max' => 20] 或 ['email', 'string', 'length' => [3, 20]]

// 使用正则表达式
['username', 'match', 'pattern' => '/^[A-Za-z_\w]+$/', 'message' => 'username仅支持字母、数字、下划线']

// 格式类型验证
['age', 'integer'] // 整数格式
['salary', 'double'] // 浮点数格式
['temperature', 'number'] // 数字格式
['isAdmin', 'boolean'] // 布尔格式
['email', 'email'] // email格式
['birthday', 'date'] // 日期格式
['website', 'url', 'defaultScheme' => 'http'] // URL格式

// 数值范围检查
['age', 'compare', 'compareValue' => 30, 'operator' => '>=']
['level', 'in', 'range' => [1, 2, 3]]

// 验证输入的两个值是否一致
['passwordRepeat', 'required'] 
['passwordRepeat', 'compare', 'compareAttribute' => 'password', 'operator' => '===']

// 验证值在数据表中唯一
['email', 'unique', 'targetClass' => CommonModelsUsers::class, 'filter' => ['status' => User::STATUS_ACTIVE], 'message' => 'email重复', 'when' => function ($model) {
    return $model->user_type == SYSTEM_NO;
}]

// 验证值在数据表中已存在
['user_email', 'exist', 'targetClass' => CommonModelsUser:class,  'targetAttribute' => ['user_email' => 'email'], 'filter' => ['status' => User::STATUS_ACTIVE],  'message' => 'There is no user with such email.']

// 使用自定义函数过滤
['email', 'filter', 'filter' => function($value) {     
    // 在此处标准化输入的email     
    return strtolower($value); 
}]

// 验证码
['verificationCode', 'captcha']

// 验证文件上传
['textFile', 'file', 'extensions' => ['txt', 'rtf', 'doc'], 'maxSize' => 1024 * 1024 * 1024]

// 验证图片上传
['avatar', 'image', 'extensions' => ['png', 'jpg'], 'minWidth' => 100, 'maxWidth' => 1000, 'minHeight' => 100, 'maxHeight' => 1000]
打赏

本文固定链接: https://www.cxy163.net/archives/2974 | 绝缘体

该日志由 绝缘体.. 于 2024年05月07日 发表在 未分类 分类下, 你可以发表评论,并在保留原文地址及作者的情况下引用到你的网站或博客。
原创文章转载请注明: Yii2.0 常用rules规则汇总 | 绝缘体
关键字: , , , ,

Yii2.0 常用rules规则汇总:等您坐沙发呢!

发表评论


快捷键:Ctrl+Enter