一、基本語法結構
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’ |