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

Yii 模型驗證規則大全:rules() 方法核心驗證器用法詳解

     編輯:PHP 綜合知識

前言

Yii 的 CActiveRecord 模型透過 rules() 方法定義資料驗證規則,是確保資料完整性的第一道防線。本文系統整理 14 種常用核心驗證器的語法、參數與實戰範例,助你快速建立健壯的表單驗證邏輯。

基礎規則範例

public function rules() {
    return array(
        // 整數驗證
        array('project_id, type_id, status_id, owner_id, requester_id', 'numerical', 'integerOnly'=>true),
        // 長度限制
        array('name', 'length', 'max'=>256),
        array('description', 'length', 'max'=>2000),
        // 安全屬性(大量賦值允許)
        array('create_time, create_user_id, update_user_id, update_time', 'safe'),
        // 搜尋場景專用屬性
        array('id, name, description, project_id, type_id, status_id, owner_id', 'on'=>'search'),
    );
}

14 種核心驗證器速查表

驗證器用途關鍵參數範例
required必填欄位— array('title,content','required')
match正則表達式pattern, allowEmpty, message array('birthday','match','pattern'=>'%^\d{4}[-/.]\d{1,2}\1\d{1,2}$%','message'=>'日期格式錯誤')
emailEmail 格式— array('user_mail','email')
urlURL 格式— array('user','url')
unique唯一性(資料庫)caseSensitive, className, message array('username','unique','caseSensitive'=>false,'className'=>'User','message'=>'用戶名已存在')
compare欄位一致性compareAttribute, message array('repassword','compare','compareAttribute'=>'password','message'=>'兩次密碼不一致')
length字串長度min, max, is, encoding array('name','length','max'=>256,'min'=>2)
in / range值在列表中range, strict array('status','in','range'=>array(1,2,3))
numerical數值型別integerOnly, min, max array('age','numerical','integerOnly'=>true,'min'=>18)
captcha驗證碼— array('verifyCode','captcha')
type型別檢查type (string, array, integer, float, date, time, datetime) array('birth_date','type','type'=>'date','dateFormat'=>'yyyy-MM-dd')
file上傳檔案types, maxSize, minSize, tooLarge, tooSmall array('avatar','file','types'=>'jpg,png','maxSize'=>1024*1024*2)
default設定預設值value, setOnEmpty array('status','default','value'=>1,'setOnEmpty'=>true)
exist資料庫存在性className, attributeName, criteria array('category_id','exist','className'=>'Category')
boolean布林值trueValue, falseValue, strict array('is_active','boolean','trueValue'=>1,'falseValue'=>0)
date日期/時間format, timestampAttribute array('expire_at','date','format'=>'yyyy-MM-dd HH:mm')
safe / unsafe大量賦值安全標記— array('token','unsafe') 防止惡意賦值

進階技巧

場景驗證

使用 on 參數指定驗證場景:

array('email', 'required', 'on'=>'register'),  // 註冊時必填
array('email', 'email', 'on'=>'register,profile'), // 註冊與編輯檔案都驗證格式

自訂驗證方法

public function rules() {
    return array(
        array('custom_field', 'validateCustom'), // 方法名 validateCustom
    );
}
public function validateCustom($attribute, $params) {
    if ($this->$attribute !== 'expected') {
        $this->addError($attribute, '自訂驗證失敗');
    }
}

條件式驗證(Yii 1.1.11+)

array('field', 'required', 'when'=>function($model){ return $model->scenario === 'admin'; })

相關專題推薦

熟練掌握這 14 種驗證器與進階用法,能讓你在幾分鐘內建立出企業級的表單驗證體系。建議收藏本文作為開發時的速查手冊!

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