Yii2 Model的一些常用rules规则

提示:打印出Validator::$builtInValidators可以看到被支持的所有validators

去除首尾空白字符
['email', 'trim']
或
['email', 'filter', 'filter' => 'trim']
 
 
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3
字段必填
['email', 'required']
 
 
  • 1
  • 1
赋予默认值
['age', 'default', 'value' => 18]
 
 
  • 1
  • 1
字符串长度
['email', 'string', 'min' => 3, 'max' => 20]
或
['email', 'string', 'length' => [3, 20]]
 
 
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3
格式类型验证
// 整数格式
['age', 'integer']
// 浮点数格式
['salary', 'double']
// 数字格式
['temperature', 'number']
// 布尔格式
['isAdmin', 'boolean']
// email格式
['email', 'email']
// 日期格式
['birthday', 'date']
// URL格式
['website', 'url', 'defaultScheme' => 'http']
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
验证码
['verificationCode', 'captcha']
 
 
  • 1
  • 1
值在数据表中是唯一的
['email', 'unique', 'targetClass' => '\common\models\Users']
 
 
  • 1
  • 1
值在数据表中已存在
['email', 'exist',
    'targetClass' => '\common\models\User',
    'filter' => ['status' => User::STATUS_ACTIVE],
    'message' => 'There is no user with such email.'],
 
 
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4
检查输入的两个值是否一致
['passwordRepeat', 'required'] // 必须要加上这一句
['passwordRepeat', 'compare', 'compareAttribute' => 'password', 'operator' => '===']
 
 
  • 1
  • 2
  • 1
  • 2
数值范围检查
['age', 'compare', 'compareValue' => 30, 'operator' => '>=']
 
 
  • 1
  • 1
['level', 'in', 'range' => [1, 2, 3]]
 
 
  • 1
  • 1
使用自定义函数过滤
['email', 'filter', 'filter' => function($value) {
    // 在此处标准化输入的email
    return strtolower($value);
}]
 
 
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4
文件上传
['textFile', 'file', 'extensions' => ['txt', 'rtf', 'doc'], 'maxSize' => 1024 * 1024 * 1024]
 
 
  • 1
  • 1
图片上传
['avatar', 'image', 'extensions' => ['png', 'jpg'],
    'minWidth' => 100, 'maxWidth' => 1000,
    'minHeight' => 100, 'maxHeight' => 1000,
]
 
 
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4
使用正则表达式
['username', 'match', 'pattern' => '/^[a-z]\w*$/i']
 
 
  • 1
  • 1

更多信息请访问官方中文手册:http://www.yiichina.com/doc/guide/2.0/tutorial-core-validators

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值