Yii 的 rules() 方法支援豐富的內建驗證器,覆蓋必填、長度、格式、業務邏輯等場景。本文整理高頻規則寫法,可直接複製到模型中按需調整。
<?php
public function rules() {
return [
// 1. 必填
[['email', 'username', 'password', 'agree', 'verifyPassword', 'verifyCode'], 'required'],
// 2. 唯一性(資料庫級)
['email', 'unique', 'message' => '用戶名已占用'],
// 3. 字符串長度
[['email', 'username'], 'string', 'max' => 64],
['username', 'string', 'min' => 2, 'max' => 7,
'tooLong' => '用戶名請輸入 4-14 個字符',
'tooShort' => '用戶名請輸入 2-7 個字'],
['password', 'string', 'min' => 6, 'max' => 22,
'tooLong' => '密碼長度 6-22 位',
'tooShort' => '密碼長度 6-22 位'],
// 4. 郵箱格式
['email', 'email', 'message' => '郵箱格式錯誤'],
// 5. 比較驗證(兩次密碼一致)
['verifyPassword', 'compare', 'compareAttribute' => 'password', 'message' => '請再次確認密碼'],
// 6. 必須同意協議(checkbox 必須為 true)
['agree', 'required', 'requiredValue' => true, 'message' => '請同意隱私協議'],
// 7. 日期時間格式
['created', 'date', 'format' => 'yyyy/MM/dd HH:mm:ss'],
// 8. 範圍驗證(枚舉值)
['superuser', 'in', 'range' => [0, 1]],
// 9. 正則驗證(用戶名僅允許字母數字下劃線連字符)
['name', 'match', 'pattern' => '/^[a-z0-9\-_]+$/i'],
// 10. 數字範圍與整數
['id', 'number', 'min' => 1, 'max' => 10, 'integerOnly' => true],
// 11. 類型驗證
['created', 'type', 'type' => 'datetime'],
// 12. 文件上傳驗證
['filename', 'file', 'allowEmpty' => true, 'types' => 'zip, rar, xls, pdf, ppt', 'maxSize' => 1024*1024*8, 'tooLarge' => '文件不超過 8M'],
['url', 'file', 'allowEmpty' => true, 'types' => 'jpg,png,gif,doc,docx,pdf,xls,xlsx,zip,rar,ppt,pptx', 'maxSize' => 1024*1024*10, 'tooLarge' => '文件大於 10M'],
// 13. 情景驗證(on 參數)
// ['field', 'required', 'on' => 'register'],
];
}
?>
[['a','b'], 'required']。message 參數可自定義錯誤提示,支援 {attribute} 佔位符。UploadedFile::getInstance() 獲取實例後再 validate()。yii\validators\Validator 實現 validateAttribute()。掌握這些規則能覆蓋 90% 以上表單驗證需求,減少控制器中的手工判斷代碼。