yii 验证器类 细说YII验证器
使用方法就是在 CActiveRecord 或 CFormModel 的子類中重寫 rules() 函數(shù),如下:
rules() 中返回的數(shù)組一般如下:
array('屬性名1,屬性名2', '驗(yàn)證器別名', 'on'=>'場景', '驗(yàn)證器屬性'=>'值', '...'=>'...')
array() 中前兩個(gè)值是必須的,后面則是可選的,當(dāng)然你要看具體驗(yàn)證器了
當(dāng)有多個(gè)屬性要使用同一個(gè)驗(yàn)證器時(shí),可以寫在同一條規(guī)則中,屬性名使用英文逗號(hào)分隔
驗(yàn)證器別名是必須的
'on'=>'場景' 是可選的, 場景是在初始化某個(gè)具體的 CActiveRecord 類時(shí)通過構(gòu)造函數(shù)設(shè)定的。
如:
在控制器類中
$model=new Post('search'); 其中 'search' 就是場景,這樣就設(shè)置了場景。當(dāng)然,CActiveRecord 類的構(gòu)造函數(shù)中,場景的默認(rèn)值是 'insert'然后,驗(yàn)證器屬性則要看某個(gè)具體驗(yàn)證器了,如 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出提示信息 進(jìn)行客戶端驗(yàn)證
2.
CFilterValidator transforms the data being validated based on a filter.
CFilterValidator is actually not a validator but a data processor.
必須是個(gè)有效的回調(diào)函數(shù) 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 booleanarray ('rememberMe','boolean'),// password needs to be authenticatedarray ('password','authenticate'));}function DataProcessor(){return "abc";}
'filter'=>array($this,'DataProcessor') $this是指這個(gè)類 這個(gè)類里面的DataProcessor函數(shù)
譬如說
if (isset ( $_POST ['LoginForm'] )) {
$model->attributes = $_POST ['LoginForm'];
$model->validate();
print_r($model->attributes);exit;
不管你輸入什么 最后都過濾成了abc
Array ( [username] => abc [password] => ?[rememberMe] => 0 )
一般習(xí)慣調(diào)用PHP自帶函數(shù) 過濾左右空格
array('username', 'filter', 'filter'=>'trim'),
3. CRegularExpressionValidator
3個(gè)參數(shù) pattern allowEmpty not
用法: array (
'mobile',
'match',
'pattern' =>'/^13[0-9]|15[^4,\\D]|18[0,5-9]\\d{8}$/',
?'message' => Yii::t ( 'activity', '無效的{attribute}' ),
),
上面就是自己寫個(gè)正則匹配手機(jī)號(hào)碼格式
4.CEmailValidator
用法:array('email', 'email'),
多email驗(yàn)證自己寫個(gè)小驗(yàn)證器:
public function rules(){return array(array('email, title, body', 'required', 'message'=>Yii::t('user','{attribute}不能為空')),array('email','mailValidator'),);}/*** 客觀需求,CEmailValidator已經(jīng)不能滿足要求* 先分割后判斷*/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才是可以通過驗(yàn)證的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中不允許重復(fù)
7.CCompareValidator
用法:array('exchange','compare','operator'=>'>',
'compareValue'=>1,
'message'=>Yii::t('trader', '{attribute} 必須為正數(shù)!')),//>0
array('exchange','compare','operator'=>'<=',
'compareValue'=>100,
'message'=>Yii::t('trader', '{attribute} 不能超過100!')),//<=100
屬性跟特殊值比較
或者:array (
'conpassword',
'compare',
'compareAttribute' => 'password'
),
屬性跟屬性比較
用法:array('username','length','max'=>12,'min'=>2,
'tooLong'=>Yii::t('user', '{attribute}至多12個(gè)字符'),
'tooShort'=>Yii::t('user', '{attribute}至少2個(gè)字符'),
'encoding'=>'utf-8'),
array('password','length','max'=>16,'min'=>6,
'tooLong'=>Yii::t('user', '{attribute}至多16個(gè)字符'),
'tooShort'=>Yii::t('user', '{attribute}至少6個(gè)字符')),
用法:array('reward','in',array(1,10,100,1000)),
reward在特定數(shù)組值內(nèi),譬如上面 reward只能有4個(gè)選擇
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'),
),
用法:array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(),'on'=>'three'),
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'),
在Yii中雖然有19個(gè)內(nèi)置的驗(yàn)證器,但是有時(shí)候并不能滿足我們的要求,這時(shí)就需要自定義一個(gè)符合自己要求的驗(yàn)證器了。
1、在驗(yàn)證器validator類中有一個(gè)createValidator方法,沒有具體研究。
2、另一種方法是自己重新定義一個(gè)驗(yàn)證器類,重新寫一個(gè)類。具體方法如下:
將 framework中提供的默認(rèn)校驗(yàn)類(這里以CUniqueValidator為例)復(fù)制到自己的web應(yīng)用目錄 extensions\validator下(該目錄不存在,自己建一個(gè)就行),更換一個(gè)文件名,假設(shè)為 ZUnique.php。打開文件,相應(yīng)類名也更改,校驗(yàn)方法根據(jù)自己需要修改。
配置config/main.php,import項(xiàng)增加一個(gè)條目
'application.extensions.validator.*',
在模型類的rules方法中引用,如:
array('username,', 'ZUniqueValidator');
提醒:可以到官方extensions下載一些現(xiàn)成validator試用。
自己也可以自己寫驗(yàn)證表達(dá)式(正則式)
array('user_qq','match','pattern'=>'/[1,9]\d{8,10}/','message'=>'qq號(hào)碼輸入不正確');///驗(yàn)證qq號(hào)碼是否是符合
array('user_addr','in','range=>array(1,2,3,4)','message'=>'你選擇的地址信息不正確');驗(yàn)證選擇的信息 是否是1 2 3 4 中的任意一個(gè)
你也可以自定義函數(shù) 進(jìn)行驗(yàn)證
array('user_name','user_check',''),
然后在該model文件中 自定義函數(shù)user_check 對user_check進(jìn)行驗(yàn)證
public function user_check(){
$len = strlen($this->user_name);
if ($len<2 ){
$this->addError('user_name','你的名字太短了');為user_name 增加錯(cuò)誤信息,不可以替換
}
}
轉(zhuǎn)載于:https://blog.51cto.com/johnzxw/1316908
總結(jié)
以上是生活随笔為你收集整理的yii 验证器类 细说YII验证器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Nginx做负载均衡报:nginx: [
- 下一篇: wdlinux 安装apc扩展