Yii2.0 常用rules规则
Posted 冰狼爱魔
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Yii2.0 常用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]
说明:打印Validator::$builtInValidators可以看到被支持的所有validators:
Array ( [boolean] => yiivalidatorsBooleanValidator [captcha] => yiicaptchaCaptchaValidator [compare] => yiivalidatorsCompareValidator [date] => yiivalidatorsDateValidator [default] => yiivalidatorsDefaultValueValidator [double] => yiivalidatorsNumberValidator [each] => yiivalidatorsEachValidator [email] => yiivalidatorsEmailValidator [exist] => yiivalidatorsExistValidator [file] => yiivalidatorsFileValidator [filter] => yiivalidatorsFilterValidator [image] => yiivalidatorsImageValidator [in] => yiivalidatorsRangeValidator [integer] => Array ( [class] => yiivalidatorsNumberValidator [integerOnly] => 1 ) [match] => yiivalidatorsRegularExpressionValidator [number] => yiivalidatorsNumberValidator [required] => yiivalidatorsRequiredValidator [safe] => yiivalidatorsSafeValidator [string] => yiivalidatorsStringValidator [trim] => Array ( [class] => yiivalidatorsFilterValidator [filter] => trim [skipOnArray] => 1 ) [unique] => yiivalidatorsUniqueValidator [url] => yiivalidatorsUrlValidator [ip] => yiivalidatorsIpValidator )
以上是关于Yii2.0 常用rules规则的主要内容,如果未能解决你的问题,请参考以下文章