yii 驗證器類 細說YII驗證器

在 yii-1.1.10.r3566 版本中,yii自帶驗證器共有 19 個。全部如下:

// CValidator.php
public static $builtInValidators=array(
 'required'=>'CRequiredValidator',               // 驗證屬性值必需有值,不能爲空
 'filter'=>'CFilterValidator',                          // 用過濾器轉換屬性的值
 'match'=>'CRegularExpressionValidator',    // 驗證屬性值匹配一個正則表達式
 'email'=>'CEmailValidator',                       // 驗證屬性值爲有一個有效的Email地址
 'url'=>'CUrlValidator',                                // 驗證屬性值是一個有效的URL
 'unique'=>'CUniqueValidator',                    // 驗證屬性值在表中的對應列中是唯一的
 'compare'=>'CCompareValidator',              // 驗證屬性值與另一個屬性的值相等
 'length'=>'CStringValidator',                      // 驗證屬性值的長度在一個範圍內
 'in'=>'CRangeValidator',                           // 驗證屬性值在一個預定義列表中
 'numerical'=>'CNumberValidator',              // 驗證屬性值是數字
 'captcha'=>'CCaptchaValidator',                // 驗證屬性的值等於一個顯示的CAPTCHA(驗證碼)的值
 'type'=>'CTypeValidator',                         // 驗證屬性值是一個指定的數據類型
 'file'=>'CFileValidator',                             // 驗證屬性值包含上傳的文件
 'default'=>'CDefaultValueValidator',          // 驗證屬性值爲分配的默認值
 'exist'=>'CExistValidator',                         // 驗證屬性值在表中的對應列中存在
 'boolean'=>'CBooleanValidator',               // 驗證屬性值是布爾值(true或false)
 'safe'=>'CSafeValidator',                         // 標記屬性值爲安全
 'unsafe'=>'CUnsafeValidator',                   // 標記屬性值爲不安全
 'date'=>'CDateValidator',                         // 驗證屬性值是日期
);


使用方法就是在 CActiveRecord 或 CFormModel 的子類中重寫 rules() 函數,如下:

public function rules() {
 return array( 
  array('username,email,password,password2', 'required'), 
  array('username', 'length', 'min'=>6, 'max'=>24), 
  array('email', 'email'), 
  array('password', 'length', 'min'=>6, 'max'=>16), 
  array('password', 'compare', 'compareAttribute'=>'password2', 'on'=>'register'),
 );
}

rules() 中返回的數組一般如下:

array('屬性名1,屬性名2', '驗證器別名', 'on'=>'場景', '驗證器屬性'=>'值', '...'=>'...')

array() 中前兩個值是必須的,後面則是可選的,當然你要看具體驗證器

當有多個屬性要使用同一個驗證器時,可以寫在同一條規則中,屬性名使用英文逗號分隔

驗證器別名是必須的

'on'=>'場景' 是可選的, 場景是在初始化某個具體的 CActiveRecord 類時通過構造函數設定的。
如:

class Post extends CActiveRecord

在控制器類中

$model=new Post('search'); 其中 'search' 就是場景,這樣就設置了場景。當然,CActiveRecord 類的構造函數中,場景的默認值是 'insert'然後,驗證器屬性則要看某個具體驗證器了,如
class CStringValidator extends CValidator{
    public $max;
    public $min;
    public $is;
    public $tooShort;
    public $tooLong;
    public $allowEmpty=true;
    public $encoding;
}

1.

CRequiredValidator
CRequiredValidator validates that the specified attribute does not have null or empty value.

用法:array('username, email, password,sex', 'required', 'message'=>Yii::t('user','{attribute}不能爲空!')),
或者 array ('username','required','requiredValue'=>100, 'message'=>Yii::t('user','{attribute}必須爲100!')),
看源碼是判斷給定屬性是否是requiredValue或者空 然後JS messages.push出提示信息 進行客戶端驗證

2.

 CFilterValidator
CFilterValidator transforms the data being validated based on a filter.
CFilterValidator is actually not a validator but a data processor.
必須是個有效的回調函數 is_callable / a valid callback
寫不對的話常常爆
屬性 "CFilterValidator.0" 未被定義. 的 CException
用法:
public function rules() {
 return array (
 // username and password are required
 /* array (
 'username, password',
 'required',
 'message' => Yii::t ( 'user', '{attribute}不能爲空' )
 ), */
array('username','filter','filter'=>array($this,'DataProcessor')),
 // rememberMe needs to be a boolean
 array (
 'rememberMe',
 'boolean'
 ),
 // password needs to be authenticated
 array (
 'password',
 'authenticate'
 )
 );
 }
 function DataProcessor()
 {
 return "abc";
 }


'filter'=>array($this,'DataProcessor') $this是指這個類 這個類裏面的DataProcessor函數
譬如說

if (isset ( $_POST ['LoginForm'] )) {
$model->attributes = $_POST ['LoginForm'];
$model->validate();
print_r($model->attributes);exit;
不管你輸入什麼 最後都過濾成了abc
Array ( [username] => abc [password] =>  [rememberMe] => 0 )


一般習慣調用PHP自帶函數 過濾左右空格
array('username', 'filter', 'filter'=>'trim'),
3. CRegularExpressionValidator
3個參數 pattern allowEmpty not
用法: array (
'mobile',
'match',
'pattern' =>'/^13[0-9]|15[^4,\\D]|18[0,5-9]\\d{8}$/',

 'message' => Yii::t ( 'activity', '無效的{attribute}' ),
),

上面就是自己寫個正則匹配手機號碼格式

4.CEmailValidator
用法:array('email', 'email'),
多email驗證自己寫個小驗證器:

public function rules()
 {
 return array(
 array('email, title, body', 'required', 'message'=>Yii::t('user','{attribute}不能爲空')),
 array('email','mailValidator'),
 );
 }
 /**
 * 客觀需求,CEmailValidator已經不能滿足要求
 * 先分割後判斷
 */
 public function mailValidator(){
 $singleEmail = strtok($this->email,' ');
 while ($singleEmail !== false)
 {
 $validator = new CEmailValidator;
 if(!$validator->validateValue($singleEmail)){
 $this->addError('email', Yii::t('user', '郵箱').'格式不正確!');
 //throw new Exception('Email is invalid', '30201');
 }
 //echo "$singleEmail<br />";
 $singleEmail = strtok(" ");
 }
 }

5.CUrlValidator
用法:array('urlname','url','validSchemes'=>array('http','https')),
這樣就只有http和https開頭的符合正則pattern的url纔是可以通過驗證的url

6.CUniqueValidator
CUniqueValidator validates that the attribute value is unique in the corresponding database table.
用法:array('username','unique','className'=>'User'),//User爲Model,username在user中不允許重複

 7.CCompareValidator
用法:
array('exchange','compare','operator'=>'>',
'compareValue'=>1,
'message'=>Yii::t('trader', '{attribute} 必須爲正數!')),//>0
array('exchange','compare','operator'=>'<=',
'compareValue'=>100,
'message'=>Yii::t('trader', '{attribute} 不能超過100!')),//<=100

屬性跟特殊值比較

或者:array (
'conpassword',
'compare',
'compareAttribute' => 'password'
),

屬性跟屬性比較

 8.CStringValidator
用法:array('username','length','max'=>12,'min'=>2,
'tooLong'=>Yii::t('user', '{attribute}至多12個字符'),
'tooShort'=>Yii::t('user', '{attribute}至少2個字符'),
'encoding'=>'utf-8'),
array('password','length','max'=>16,'min'=>6,
'tooLong'=>Yii::t('user', '{attribute}至多16個字符'),
'tooShort'=>Yii::t('user', '{attribute}至少6個字符')),


 9.CRangeValidator
用法:array('reward','in',array(1,10,100,1000)),
 reward在特定數組值內,譬如上面 reward只能有4個選擇


 10.CNumberValidator

CNumberValidator validates that the attribute value is a number.
用法:array('username','numerical','integerOnly'=>true,'min'=>0,'max'=>1000,
'tooBig'=>Yii::t('user', '{attribute}不能大於1000'),
'tooSmall'=>Yii::t('user', '{attribute}必須大於0'),
),

 11.CCaptchaValidator
用法:array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(),'on'=>'three'),


 12.CTypeValidator
Valid values include 'string', 'integer', 'float', 'array', 'date', 'time' and 'datetime'.
用法:array('username','type','type'=>'date','dateFormat'=>'MM/dd/yyyy'),


 13.CFileValidator
用法:array('filename', 'file', 'allowEmpty'=>true, 'types'=>'zip, rar, xls, pdf, ppt'),
 14.CDefaultValueValidator
用法:array('created','default','value'=>new CDbExpression('NOW()'),'setOnEmpty'=>false),

 15.CExistValidator

用法:array('username','exist','className'=>'User'),

 18.CUnsafeValidator 19.CDateValidator用法:array('username','date','format'=>'yyyy-MM-dd'),


在Yii中雖然有19個內置的驗證器,但是有時候並不能滿足我們的要求,這時就需要自定義一個符合自己要求的驗證器了。

1、在驗證器validator類中有一個createValidator方法,沒有具體研究。

2、另一種方法是自己重新定義一個驗證器類,重新寫一個類。具體方法如下:

  1. 將 framework中提供的默認校驗類(這裏以CUniqueValidator爲例)複製到自己的web應用目錄 extensions\validator下(該目錄不存在,自己建一個就行),更換一個文件名,假設爲 ZUnique.php。打開文件,相應類名也更改,校驗方法根據自己需要修改。

  2. 配置config/main.php,import項增加一個條目
    'application.extensions.validator.*',

  3. 在模型類的rules方法中引用,如:
    array('username,', 'ZUniqueValidator');

提醒:可以到官方extensions下載一些現成validator試用。


自己也可以自己寫驗證表達式(正則式)

array('user_qq','match','pattern'=>'/[1,9]\d{8,10}/','message'=>'qq號碼輸入不正確');///驗證qq號碼是否是符合


array('user_addr','in','range=>array(1,2,3,4)','message'=>'你選擇的地址信息不正確');////驗證選擇的信息 是否是1 2 3 4 中的任意一個


你也可以自定義函數 進行驗證

array('user_name','user_check',''),

然後在該model文件中 自定義函數user_check 對user_check進行驗證

public function user_check(){

$len = strlen($this->user_name);

if ($len<2 ){

$this->addError('user_name','你的名字太短了');////爲user_name 增加錯誤信息,不可以替換

}


}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章