Yii 的 rules() 方法是模型數據驗證的核心。本文整理了開發中最高頻的驗證規則模板,涵蓋基礎驗證、格式檢查、業務邏輯、文件上傳等場景,可直接複製到模型中按需調整。
public function rules() {
return [
// 1. 必填驗證
[['email', 'username', 'password', 'agree', 'verifyPassword', 'verifyCode'], 'required'],
// 2. 唯一性驗證(針對 email 字段)
['email', 'unique', 'message' => '用戶名已被佔用'],
// 3. 字符串長度:最大長度
[['email', 'username'], 'string', 'max' => 64],
// 4. 字符串長度:區間限制 + 自定義錯誤信息
['username', 'string', 'min' => 2, 'max' => 7,
'tooShort' => '用戶名至少 2 個字符',
'tooLong' => '用戶名最多 7 個字符'],
// 5. 密碼長度區間
['password', 'string', 'min' => 6, 'max' => 22,
'tooShort' => '密碼至少 6 位',
'tooLong' => '密碼最多 22 位'],
// 6. Email 格式驗證
['email', 'email', 'message' => '郵箱格式不正確'],
// 7. 兩字段值比較(確認密碼)
['verifyPassword', 'compare', 'compareAttribute' => 'password',
'message' => '兩次密碼不一致'],
// 8. 必須為 true(同意協議)
['agree', 'required', 'requiredValue' => true,
'message' => '請同意隱私協議條款'],
// 9. 日期時間格式
['created', 'date', 'format' => 'yyyy/MM/dd HH:mm:ss'],
// 10. 範圍驗證(枚舉值)
['superuser', 'in', 'range' => [0, 1]],
// 11. 正則表達式驗證
['name', 'match', 'pattern' => '/^[a-z0-9\-_]+$/i'],
// 12. 數字範圍 + 僅整數
['id', 'number', 'min' => 1, 'max' => 10, 'integerOnly' => true],
// 13. 類型驗證
['created', 'type', 'type' => 'datetime'], // 支持 integer, float, string, array, date, time, datetime
// 14. 文件上傳:基礎配置
['filename', 'file',
'allowEmpty' => true,
'extensions' => 'zip, rar, xls, pdf, ppt',
'maxSize' => 800 * 1024, // 800KB
'tooLarge' => '文件不得超過 800KB'],
// 15. 文件上傳:完整配置(多格式、大小限制、錯誤信息)
['url', 'file',
'allowEmpty' => true,
'extensions' => 'jpg, png, gif, doc, docx, pdf, xls, xlsx, zip, rar, ppt, pptx',
'maxSize' => 10 * 1024 * 1024, // 10MB
'tooLarge' => '文件大於 10MB,上傳失敗!請上傳小於 10MB 的文件!'],
];
}
| 驗證器 | 關鍵參數 | 說明 |
|---|---|---|
| required | requiredValue, strict | 必填;requiredValue 指定必須匹配的值(如 true) |
| string | min, max, tooShort, tooLong | 長度驗證,編碼按 UTF-8 計算字符數 |
| checkDNS, enableIDN | 可選檢查 MX 記錄、支援國際化域名 | |
| compare | compareAttribute, compareValue, operator | 比較兩字段或與常量,operator 支持 ==, ===, !=, !==, >, >=, <, <= |
| unique | targetClass, targetAttribute, filter | 唯一性,可跨模型、多字段聯合唯一 |
| in | range, strict | 值必須在 range 陣列中 |
| match | pattern, not | 正則匹配,not=true 表示不匹配才通過 |
| number | min, max, integerOnly | 數值範圍,integerOnly 強制整數 |
| file | extensions, mimeTypes, maxSize, minSize, maxFiles, checkExtensionByMimeType | 文件驗證核心,支援多文件上傳 |
| date | format, timestampAttribute | 日期格式,可自動填充時間戳屬性 |
// 模型中定義場景
public function scenarios() {
return [
'register' => ['username', 'email', 'password', 'verifyPassword', 'agree'],
'login' => ['username', 'password'],
'profile' => ['email', 'avatar'], // avatar 為文件上傳字段
];
}
// 控制器中指定場景
$model = new User(['scenario' => 'register']);
// 或
$model->scenario = 'register';
['state', 'required', 'when' => function ($model) {
return $model->country === 'USA'; // 只有美國用戶必填州
}],
// 內聯匿名函數
['password', function ($attribute, $params, $validator) {
if (!preg_match('/[A-Z]/', $this->$attribute)) {
$this->addError($attribute, '密碼必須包含大寫字母');
}
}],
// 獨立類(可複用)
use yii\validators\Validator;
class StrongPasswordValidator extends Validator {
public function validateAttribute($model, $attribute) {
$value = $model->$attribute;
if (strlen($value) < 8 || !preg_match('/[A-Z]/', $value) || !preg_match('/\d/', $value)) {
$this->addError($model, $attribute, '密碼需 8 位以上、含大寫、含數字');
}
}
}
// 使用
['password', StrongPasswordValidator::class],
// 控制器處理
public function actionUpload() {
$model = new UploadForm();
$model->file = UploadedFile::getInstance($model, 'file');
if ($model->validate() && $model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension)) {
return '上傳成功';
}
return $model->getErrors();
}
saveAs(),並自行處理文件名衝突'operator' => '==' 為寬鬆比較,避免類型不匹配導致誤判preg_match(),模式需包含分隔符(如 /^pattern$/)Yii 的驗證系統靈活強大,核心在於 聲明式配置 + 場景隔離 + 可擴展驗證器。合理組合內置規則,90% 的業務驗證無需寫自定義邏輯;剩餘 10% 用內聯函數或獨立驗證器類解決,保持模型代碼整潔可維護。