当前位置: 首页 > news >正文

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

一、基本语法结构

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
['email', 'email'],
['age', 'integer'],
['website', 'url', 'defaultScheme' => 'http'],

范围验证类:

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

存在性验证:

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

其他验证:

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

2、行内验证器

在模型内部定义方法

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

3、匿名函数验证器

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

三、高级规则配置

1、条件验证(when)

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

2、客户端验证

['captcha', 'captcha', 'captchaAction' => 'site/captcha', 'skipOnEmpty' => false],

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

['password', 'required', 'on' => 'register'],
['email', 'required', 'except' => 'guest'],

4、空值处理

['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’

相关文章:

  • ntdll!CsrServerApiRoutine函数--csrsrv!CsrCallServerFromServer什么时候被调用?
  • 2025.05.07-华为机考第二题200分
  • 动态规划之花园
  • 高并发内存池(一):项目简介+定长内存池的实现
  • C25-数组应用及练习
  • iTwin 数据报表(只是简单的原型不代表实现)
  • 解决 TimeoutError: [WinError 10060] 在 FramePack项目中连接 Hugging Face 超时的问题
  • ​​阿里云服务器:数字世界的“基因剪刀”与未来实验室​
  • 联想Horizon 2系列电脑 参数
  • C++面向对象 继承
  • python安装pyqt5失败
  • ESP32- 开发笔记- 软件开发 6 蓝牙协议栈 1
  • 【SpringCloud GateWay】Connection prematurely closed BEFORE response 报错分析与解决方案
  • [Android] WPS Office11.4.1.6政务定制版
  • windows使用bat脚本激活conda环境
  • Docker + Watchtower 实现容器自动更新:高效运维的终极方案
  • Linux 信号(下篇)
  • 趣味编程:梦幻万花筒
  • QT人工智能篇-opencv
  • QT聊天项目DAY09
  • 陈宝良 高寿仙 彭勇︱明清社会的皇权、商帮与市井百态
  • 国际足联女子世界杯再次扩军,2031年起增至48支球队
  • 图忆|红场阅兵:俄罗斯30年来的卫国战争胜利日阅兵式
  • 2025柯桥时尚周启幕:国际纺都越来越时尚
  • 阿里CEO:将以饱和式投入打法,聚焦几大核心战役
  • 治沙“异瞳”男生疑似摆拍,团队称合作12天多期视频为策划拍摄