/**
* 细说YII验证器
* @author insun
* http://yxmhero1989.blog.163.com
*
*/
在 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.用法:array('username, email, password,sex', 'required', 'message'=>Yii::t('user','{attribute}不能为空!')),
CRequiredValidator CRequiredValidator validates that the specified attribute does not have null or empty value.
或者 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验证自己写个小验证器:http://yxmhero1989.blog.163.com/blog/static/1121579562012230115215567/
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中不允许重复
或者:array (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 属性跟特殊值比较
'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.CNumberValidatorCNumberValidator 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'),16.CBooleanValidator 用法:array('agreeService', 'boolean','trueValue'=>1, 'falseValue'=>-1, 'message'=>'请同意insun网服务条款!' ),
17.CSafeValidator 用法:// The following rule is used by search(). // Please remove those attributes that should not be searched. array('traderId, exchange', 'safe', 'on'=>'search'),
18.CUnsafeValidator 19.CDateValidator 用法:array('username','date','format'=>'yyyy-MM-dd'),
在Yii中虽然有19个内置的验证器,但是有时候并不能满足我们的要求,这时就需要自定义一个符合自己要求的验证器了。
1、在验证器validator类中有一个createValidator方法,没有具体研究。
2、另一种方法是自己重新定义一个验证器类,重新写一个类。具体方法如下:
- 将 framework中提供的默认校验类(这里以CUniqueValidator为例)复制到自己的web应用目录 extensions\validator下(该目录不存在,自己建一个就行),更换一个文件名,假设为 ZUnique.php。打开文件,相应类名也更改,校验方法根据自己需要修改。
- 配置config/main.php,import项增加一个条目
'application.extensions.validator.*', - 在模型类的rules方法中引用,如:
array('username,', 'ZUniqueValidator');
贴一张网站制作群上某位同学拍 的:我很喜欢