Yii2.0 模型规则(rules)详解

一、基本语法结构

php 复制代码
public function rules()
{
    return [
        // 规则1
        [['attribute1', 'attribute2'], 'validator', 'options' => value, ...],
        
        // 规则2
        ['attribute', 'validator', 'options' => value, ...],
        
        // 规则3...
    ];
}

二、规则类型分类

1、核心验证器(内置验证器)

格式验证类:

  • boolean:验证是否为布尔值
  • email:验证是否为有效邮箱格式
  • string:验证是否为字符串
  • number:验证是否为数字
  • double:验证是否为浮点数
  • integer:验证是否为整数
  • date:验证是否为日期格式
  • time:验证是否为时间格式
  • datetime:验证是否为日期时间格式
  • url:验证是否为有效URL
php 复制代码
['email', 'email'],
['age', 'integer'],
['website', 'url', 'defaultScheme' => 'http'],

范围验证类:

  • in:验证是否在给定列表
  • notIn:验证值是否不在给定列表中
  • range:验证数值是否在范围内
  • compare:比较两个属性的值
php 复制代码
['status', 'in', 'range' => [1, 2, 3]],
['priority', 'compare', 'compareValue' => 10, 'operator' => '>='],

存在性验证:

  • required: 验证是否为必填
  • default:验证默认值(非严格验证)
  • exist:验证值是否存在与数据库中
  • unique:验证值在数据库中是否唯一
php 复制代码
[['username', 'password'], 'required'],
['category_id', 'exist', 'targetClass' => Category::class, 'targetAttribute' => 'id'],
['email', 'unique', 'targetClass' => User::class],

其他验证:

  • filter: 数据过滤
  • match:正则表达式验证
  • trim:去除首尾空格
  • safe:标记属性为安全(不验证)
php 复制代码
['username', 'match', 'pattern' => '/^[a-z]\w*$/i'],
['content', 'filter', 'filter' => 'strip_tags'],
['auth_key', 'default', 'value' => Yii::$app->security->generateRandomString()],

2、行内验证器

在模型内部定义方法

php 复制代码
public function rules()
{
    return [
        ['password', 'validatePassword'],
    ];
}

public function validatePassword($attribute, $params)
{
    if (strlen($this->$attribute) < 8) {
        $this->addError($attribute, '密码长度不能少于8个字符');
    }
}

3、匿名函数验证器

php 复制代码
public function rules()
{
    return [
        ['agree', function($attribute, $params) {
            if ($this->$attribute != 1) {
                $this->addError($attribute, '必须同意条款');
            }
        }],
    ];
}

三、高级规则配置

1、条件验证(when)

php 复制代码
['state', 'required', 'when' => function($model) {
    return $model->country == 'USA';
}],

2、客户端验证

php 复制代码
['captcha', 'captcha', 'captchaAction' => 'site/captcha', 'skipOnEmpty' => false],

3、指定场景验证(on/except)

php 复制代码
['password', 'required', 'on' => 'register'],
['email', 'required', 'except' => 'guest'],

4、空值处理

php 复制代码
['description', 'default', 'value' => null], // 允许为空
['status', 'required', 'skipOnEmpty' => false], // 不允许空字符串

四、规则选项详解

通用选项

选项 说明 示例 解释 用法 结果
message 定义错误信息 'message'=> '{attribute}不能为空' {attribute}为占位符 [['username', 'password'], 'required', 'message'=> '{attribute}不能为空'] username不能为空或者password不能为空
skipOnEmpty 为空时是否跳过验证 'skipOnEmpty' => true
skipOnError 当属性已有错误时是否跳过 'skipOnError' => true
when 条件验证回调 'when' => function($model) { ... }
on 适用场景 'on' => ['create', 'update']
except 排除场景 'except' => 'delete'
相关推荐
前端世界17 小时前
Python 正则表达式实战:用 Match 对象轻松解析拼接数据流
python·正则表达式·php
苏琢玉20 小时前
用 PHP 玩向量数据库:一个从小说网站开始的小尝试
php·composer
wuk99821 小时前
ThinkPHP 6框架常见错误:htmlentities()函数参数类型问题解决
php
万岳软件开发小城1 天前
开源与定制化对比:哪种在线教育系统源码更适合教育培训APP开发?
开源·php·软件开发·在线教育系统源码·教育小程序·教育app开发
lskblog1 天前
Composer安装教程及国内镜像设置(含腾讯云、阿里云镜像)
阿里云·php·腾讯云·laravel·composer
m0_738120721 天前
CTFshow系列——PHP特性Web93-96
开发语言·安全·web安全·php·ctfshow
@CLoudbays_Martin111 天前
为什么动态视频业务内容不可以被CDN静态缓存?
java·运维·服务器·javascript·网络·python·php
learning_tom2 天前
HTML图片标签及路径详解
linux·服务器·php
魔道不误砍柴功2 天前
Mac 能够连Wife,但是不能上网问题解决
网络·macos·php
搬码临时工2 天前
怎样让外网计算机访问局域网计算机?通过公网地址访问不同内网服务的设置方法
开发语言·php