cccicl
cccicl
发布于 1个月前

Yii2 rules验证规则

去除首尾空白字符

['email', 'trim'] 或 ['email', 'filter', 'filter' => 'trim']

字段必填
['email', 'required']

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

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

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

验证码

['verificationCode', 'captcha']

值在数据表中是唯一的

['email', 'unique', 'targetClass' => 'commonmodelsUsers']

值在数据表中已存在

['email', 'exist',     'targetClass' => 'commonmodelsUser',     'filter' => ['status' => User::STATUS_ACTIVE],     'message' => 'There is no user with such email.']

检查输入的两个值是否一致
['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']

提示:打印出Validator::$builtInValidators可以看到被支持的所有validators
Array
(
    [boolean] => yii\validators\BooleanValidator
    [captcha] => yii\captcha\CaptchaValidator
    [compare] => yii\validators\CompareValidator
    [date] => yii\validators\DateValidator
    [default] => yii\validators\DefaultValueValidator
    [double] => yii\validators\NumberValidator
    [each] => yii\validators\EachValidator
    [email] => yii\validators\EmailValidator
    [exist] => yii\validators\ExistValidator
    [file] => yii\validators\FileValidator
    [filter] => yii\validators\FilterValidator
    [image] => yii\validators\ImageValidator
    [in] => yii\validators\RangeValidator
    [integer] => Array
        (
            [class] => yii\validators\NumberValidator
            [integerOnly] => 1
        )

    [match] => yii\validators\RegularExpressionValidator
    [number] => yii\validators\NumberValidator
    [required] => yii\validators\RequiredValidator
    [safe] => yii\validators\SafeValidator
    [string] => yii\validators\StringValidator
    [trim] => Array
        (
            [class] => yii\validators\FilterValidator
            [filter] => trim
            [skipOnArray] => 1
        )

    [unique] => yii\validators\UniqueValidator
    [url] => yii\validators\UrlValidator
    [ip] => yii\validators\IpValidator
)
©2020 edoou.com   京ICP备16001874号-3