首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

Yii 1.x rules 驗證規則大全與最佳實踐備忘

     編輯:PHP 相關知識

Yii 1.x rules 驗證規則大全與最佳實踐備忘

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 的文件!'
        ),
    );
}

核心驗證器參數速查表

驗證器關鍵參數說明
requiredrequiredValue, strict必填,可指定必須等於某值
uniqueclassName, attributeName, criteria資料庫唯一性,支援複合條件
lengthmin, max, tooShort, tooLong字符串長度,支援 UTF-8
emailcheckMX, allowNameRFC 822 郵箱格式
comparecompareAttribute, compareValue, operator比較運算符預設 ==
dateformat, timestampAttributestrptime 格式化字符串
inrange, strict, not枚舉值白/黑名單
matchpattern, notPCRE 正則
numericalmin, max, integerOnly, tooSmall, tooBig數值範圍
typetype, typeNotPHP 類型判斷
filetypes, maxSize, minSize, maxFiles, tooLarge, tooSmall, tooMany, wrongType上傳文件完整驗證

進階技巧

  • 場景驗證: 使用 'on' => 'scenarioName' 區分註冊、登錄、後台編輯等不同規則集。
  • 條件驗證: 結合 validateAttribute() 在運行時動態決定是否驗證某字段。
  • 自定義驗證器: 繼承 CValidator 實現複雜業務邏輯(如手機號歸屬地、身份證校驗碼)。
  • 客戶端驗證: 開啟 enableClientValidation,Yii 自動生成 jQuery 驗證腳本,提升用戶體驗。

常見坑點提醒

  1. unique 驗證器預設查詢模型對應表,跨表需指定 className 和 attributeName。
  2. file 驗證器的 maxSize 單位為位元組,需小於 php.ini 的 upload_max_filesize 與 post_max_size。
  3. date 格式字符串使用 strptime 語法,非 date() 語法(如 %Y 而非 Y)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved