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

Yii 1.x 表單驗證規則大全:內建驗證器與自訂規則實戰

     編輯:PHP 相關知識

CModel::rules() 完整驗證規則寫法與實戰範例

Yii 表單模型(CFormModel)與 AR 模型皆透過 rules() 方法宣告驗證規則。本文彙整所有內建驗證器別名、參數用法,並提供完整的聯絡表單與使用者註冊實戰範例。

內建驗證器速查表

別名類別用途
booleanCBooleanValidator值必須為 trueValue/falseValue
captchaCCaptchaValidator驗證碼比對
compareCCompareValidator比較兩屬性或與常數
emailCEmailValidatorEmail 格式
defaultCDefaultValueValidator設定預設值
existCExistValidator值存在於資料表欄位
fileCFileValidator上傳檔案驗證
filterCFilterValidator套用過濾器轉換屬性
inCRangeValidator值在指定清單中
lengthCStringValidator字串長度範圍
matchCRegularExpressionValidator正則表達式比對
numericalCNumberValidator數值格式
requiredCRequiredValidator不可為空
typeCTypeValidator資料型別
uniqueCUniqueValidator資料表欄位唯一
urlCUrlValidatorURL 格式

完整聯絡表單範例

class ContactForm extends CFormModel {
    public $contact, $tel, $fax, $zipcode, $addr, $mobile, $email, $website, $qq, $msn;

    public function rules() {
        return [
            ['contact', 'required', 'on' => 'edit', 'message' => '聯絡人必填.'],
            ['contact', 'length', 'on' => 'edit', 'min' => 2, 'max' => 10,
                'tooShort' => '聯絡人長度 2-10 字元.', 'tooLong' => '聯絡人長度 2-10 字元.'],
            ['tel', 'match', 'pattern' => '/^(\d{3}-|\d{4}-)(\d{8}|\d{7})$/', 'message' => '電話格式錯誤.'],
            ['fax', 'match', 'pattern' => '/^(\d{3}-|\d{4}-)(\d{8}|\d{7})$/', 'message' => '傳真格式錯誤.'],
            ['mobile', 'match', 'pattern' => '/^13[0-9]{9}$|15[0189]{1}[0-9]{8}$|189[0-9]{8}$/', 'message' => '手機格式錯誤.'],
            ['email', 'email', 'on' => 'edit', 'message' => 'Email 格式錯誤.'],
            ['zipcode', 'required', 'on' => 'edit', 'message' => '郵遞區號必填.'],
            ['zipcode', 'numerical', 'on' => 'edit', 'message' => '郵遞區號 6 位數字.'],
            ['zipcode', 'length', 'on' => 'edit', 'min' => 6, 'max' => 6, 'tooShort' => '郵遞區號 6 位.', 'tooLong' => '郵遞區號 6 位.'],
            ['website', 'url', 'on' => 'edit', 'message' => '網址格式錯誤.'],
            ['qq', 'match', 'pattern' => '/^[1-9]{1}[0-9]{4,11}$/', 'message' => 'QQ 號碼格式錯誤.'],
            ['msn', 'email', 'on' => 'edit', 'message' => 'MSN 格式錯誤.'],
        ];
    }
}

進階:使用者模型完整驗證(含自訂規則)

class User extends CActiveRecord {
    public $password2, $verify, $fjg; // 非資料庫欄位

    public function rules() {
        return [
            ['mobile_phone', 'unique', 'message' => '手機已存在!'],
            ['mobile_phone', 'match', 'pattern' => '/^(13|15|18)[0-9]{9}$/', 'message' => '手機格式錯誤.'],
            ['phone', 'match', 'pattern' => '/^(\d{3}-|\d{4}-)?(\d{8}|\d{7})?$/', 'message' => '座機格式錯誤.'],
            ['fax', 'match', 'pattern' => '/^(\d{3}-|\d{4}-)(\d{8}|\d{7})?$/', 'message' => '傳真格式錯誤.'],
            ['email_address', 'email', 'message' => 'Email 格式錯誤.'],
            // 密碼確認
            ['password2', 'compare', 'compareAttribute' => 'password', 'message' => '兩次密碼不一致', 'on' => 'register,regonter'],
            ['qq', 'match', 'pattern' => '/^[1-9]{1}[0-9]{4,11}$/', 'message' => 'QQ 格式錯誤.'],
            ['type,certificate_id,company_type,nationality,yyzz_id,status,level,create_by_id,create_time,update_time', 'numerical', 'integerOnly' => true],
            ['verify', 'numerical', 'message' => '驗證碼錯誤', 'integerOnly' => true],
            ['name,user_type,tuijianren', 'length', 'max' => 20],
            ['password', 'length', 'max' => 100],
            ['email_address,business', 'length', 'max' => 50],
            ['communication_address,money,yhzh,yhmc,industry,company,register_address,yhdh,shangbiao,zhuanli,gongshang', 'length', 'max' => 255],
            ['role_id', 'default', 'setOnEmpty' => true, 'value' => 10],
            ['shangbiao', 'default', 'setOnEmpty' => true, 'value' => '0,0'],
            ['zhuanli', 'default', 'setOnEmpty' => true, 'value' => '0,0'],
            ['gongshang', 'default', 'setOnEmpty' => true, 'value' => '0,0'],
            ['password', 'default', 'setOnEmpty' => true, 'value' => '123456'],
            // 自訂驗證方法
            ['verify', 'checkVerify', 'on' => 'register'],
            ['email_address', 'checkemail', 'on' => 'regonter'],
            // 搜尋場景安全屬性
            ['id,role_id,name,password,user_type,email_address,tuijianren,shangbiao,company_type,zhuanli,gongshang,money,yhzh,yhmc,yyzz_id,yhdh,type,level,phone,qq,mobile_phone,fax,communication_address,nationality,industry,company,business,register_address,certificate,status,create_by_id,create_time,update_time', 'safe', 'on' => 'search'],
        ];
    }

    // 自訂驗證:手機驗證碼
    public function checkVerify($attribute, $params) {
        $model = new Mess();
        $record = $model->find([
            'condition' => 'suij=:suij AND tel=:tel AND type>:type AND time>:time',
            'params' => [':suij' => $this->verify, ':tel' => $this->mobile_phone, ':type' => 0, ':time' => time()-3600],
            'select' => 'id'
        ]);
        if (!$record || $record['id'] < 1) {
            $this->addError('verify', '驗證碼不正確。');
        } elseif ($this->password === $this->password2) {
            $model->updateAll(['type' => 0], ['condition' => 'suij=:sj', 'params' => [':sj' => $this->verify]]);
        }
    }
}

關鍵技巧總結

  • 場景:'on' => 'create,update' 限定規則生效場景。
  • 自訂驗證:方法簽名 function checkXxx($attribute, $params),用 $this->addError($attribute, '訊息') 回報錯誤。
  • 非資料庫欄位:在模型宣告 public $field,配合 safe 規則允許大量指派。
  • 預設值:default 驗證器在驗證階段填入,不寫入資料庫除非 save()。

善用內建驗證器覆蓋 90% 需求,複雜業務邏輯再以自訂方法補足,保持 rules() 清晰可維護。

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