May
07
2024
Yii2.0 常用rules规则汇总
作者:
绝缘体.. 发布:
2024-05-07 11:21 分类:
未分类 阅读:
抢沙发
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]
微信扫一扫,打赏作者吧~