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

Yii 2.0 Rules 驗證規則大全:從必填、唯一到文件上傳的完整配置指南

     編輯:PHP 綜合知識

Yii 的 rules() 方法是模型數據驗證的核心。本文整理了開發中最高頻的驗證規則模板,涵蓋基礎驗證、格式檢查、業務邏輯、文件上傳等場景,可直接複製到模型中按需調整。

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

核心驗證器參數速查表

驗證器關鍵參數說明
requiredrequiredValue, strict必填;requiredValue 指定必須匹配的值(如 true)
stringmin, max, tooShort, tooLong長度驗證,編碼按 UTF-8 計算字符數
emailcheckDNS, enableIDN可選檢查 MX 記錄、支援國際化域名
comparecompareAttribute, compareValue, operator比較兩字段或與常量,operator 支持 ==, ===, !=, !==, >, >=, <, <=
uniquetargetClass, targetAttribute, filter唯一性,可跨模型、多字段聯合唯一
inrange, strict值必須在 range 陣列中
matchpattern, not正則匹配,not=true 表示不匹配才通過
numbermin, max, integerOnly數值範圍,integerOnly 強制整數
fileextensions, mimeTypes, maxSize, minSize, maxFiles, checkExtensionByMimeType文件驗證核心,支援多文件上傳
dateformat, 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';

條件驗證(when / whenClient)

['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();
}

常見誤區避雷

  • unique 驗證需資料庫連接:單元測試時記啟用 fixtures 或 mock DB
  • file 驗證器僅檢查上傳元數據:實際保存需調用 saveAs(),並自行處理文件名衝突
  • compare 默認嚴格模式:'operator' => '==' 為寬鬆比較,避免類型不匹配導致誤判
  • 正則修飾符:Yii 內部使用 preg_match(),模式需包含分隔符(如 /^pattern$/)

總結

Yii 的驗證系統靈活強大,核心在於 聲明式配置 + 場景隔離 + 可擴展驗證器。合理組合內置規則,90% 的業務驗證無需寫自定義邏輯;剩餘 10% 用內聯函數或獨立驗證器類解決,保持模型代碼整潔可維護。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved