Yii 框架的 rules() 方法是模型數據驗證的核心。本文匯總 12 類高頻驗證規則,涵蓋必填、唯一、長度、郵箱、比較、協議確認、日期、範圍、正則、數字、類型、文件上傳等場景,並附帶錯誤訊息自定義技巧,供開發快速查閱複製。
public function rules() {
return array(
// 1. 必填驗證
array('email, username, password, agree, verifyPassword, verifyCode', 'required'),
// 2. 唯一性驗證(針對資料庫字段)
array('email', 'unique', 'message' => '用戶名已占用'),
// 3. 最大長度
array('email, username', 'length', 'max' => 64),
// 4. 長度範圍 + 自定義錯誤訊息
array('username', 'length', 'max' => 7, 'min' => 2,
'tooLong' => '用戶名請輸入長度為 4-14 個字符',
'tooShort' => '用戶名請輸入長度為 2-7 個字'),
// 5. 密碼長度範圍
array('password', 'length', 'max' => 22, 'min' => 6,
'tooLong' => '密碼請輸入長度為 6-22 位字符',
'tooShort' => '密碼請輸入長度為 6-22 位字符'),
// 6. 郵箱格式
array('email', 'email', 'message' => '郵箱格式錯誤'),
// 7. 比較驗證(兩次密碼一致)
array('verifyPassword', 'compare', 'compareAttribute' => 'password', 'message' => '請再輸入確認密碼'),
// 8. 必須為 true(協議勾選)
array('agree', 'required', 'requiredValue' => true, 'message' => '請確認是否同意隱私權協議條款'),
// 9. 日期格式
array('created', 'date', 'format' => 'yyyy/MM/dd HH:mm:ss'),
// 10. 範圍驗證(枚舉值)
array('superuser', 'in', 'range' => array(0, 1)),
// 11. 正則驗證
array('name', 'match', 'pattern' => '/^[a-z0-9\-_]+$/'),
// 12. 數字驗證(整數、範圍)
array('id', 'numerical', 'min' => 1, 'max' => 10, 'integerOnly' => true),
// 13. 類型驗證
array('created', 'type', 'type' => 'datetime'), // integer, float, string, array, date, time, datetime
// 14. 文件上傳驗證(基礎)
array('filename', 'file', 'allowEmpty' => true, 'types' => 'zip, rar, xls, pdf, ppt', 'tooLarge' => '圖片不要超過 800K'),
// 15. 文件上傳驗證(完整參數)
array('url', 'file',
'allowEmpty' => true,
'types' => 'jpg,png,gif,doc,docx,pdf,xls,xlsx,zip,rar,ppt,pptx',
'maxSize' => 1024 * 1024 * 10, // 10MB
'tooLarge' => '文件大於 10M,上傳失敗!請上傳小於 10M 的文件!'
),
);
}
| 驗證器 | 關鍵參數 | 說明 |
|---|---|---|
| required | requiredValue, strict | 必填,可指定必須等於某值 |
| unique | className, attributeName, criteria | 資料庫唯一性,支援複合條件 |
| length | min, max, tooShort, tooLong | 字符串長度,支援 UTF-8 |
| checkMX, allowName | RFC 822 郵箱格式 | |
| compare | compareAttribute, compareValue, operator | 比較運算符預設 == |
| date | format, timestampAttribute | strptime 格式化字符串 |
| in | range, strict, not | 枚舉值白/黑名單 |
| match | pattern, not | PCRE 正則 |
| numerical | min, max, integerOnly, tooSmall, tooBig | 數值範圍 |
| type | type, typeNot | PHP 類型判斷 |
| file | types, maxSize, minSize, maxFiles, tooLarge, tooSmall, tooMany, wrongType | 上傳文件完整驗證 |
'on' => 'scenarioName' 區分註冊、登錄、後台編輯等不同規則集。validateAttribute() 在運行時動態決定是否驗證某字段。CValidator 實現複雜業務邏輯(如手機號歸屬地、身份證校驗碼)。enableClientValidation,Yii 自動生成 jQuery 驗證腳本,提升用戶體驗。unique 驗證器預設查詢模型對應表,跨表需指定 className 和 attributeName。file 驗證器的 maxSize 單位為位元組,需小於 php.ini 的 upload_max_filesize 與 post_max_size。date 格式字符串使用 strptime 語法,非 date() 語法(如 %Y 而非 Y)。