/**
* 细说YII验证器
* @author insun
* http://yxmhero1989.blog.163.com
*
*/php
在 yii-1.1.10.r3566 版本中,yii 自带的验证器共有 19 个。所有以下:html
// 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() 函数,以下:web
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() 中前两个值是必须的,后面则是可选的,固然你要看具体验证器了安全
当有多个属性要使用同一个验证器时,能够写在同一条规则中,属性名使用英文逗号分隔app
验证器别名是必须的yii
'on'=>'场景' 是可选的, 场景是在初始化某个具体的 CActiveRecord 类时经过构造函数设定的。
如:函数class Post extends CActiveRecord在控制器类中ui
$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验证本身写个小验证器: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中不容许重复
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'),
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个内置的验证器,可是有时候并不能知足咱们的要求,这时就须要自定义一个符合本身要求的验证器了。
一、在验证器validator类中有一个createValidator方法,没有具体研究。
二、另外一种方法是本身从新定义一个验证器类,从新写一个类。具体方法以下:
提醒:能够到官方extensions下载一些现成validator试用。
Reference:
http://www.myexception.cn/open-source/409237.htmlhttp://1051821910.blog.163.com/blog/static/11699594020111128111524891/http://hudeyong926.iteye.com/blog/1276422http://blog.sina.com.cn/s/blog_71ef89140100x74l.html关于自定义rules验证器的param选项http://www.yiiframework.com/forum/index.php/topic/22288-%E5%85%B3%E4%BA%8E%E8%87%AA%E5%AE%9A%E4%B9%89rules%E9%AA%8C%E8%AF%81%E5%99%A8%E7%9A%84param%E9%80%89%E9%A1%B9/转载自:http://yxmhero1989.blog.163.com/blog/static/112157956201302510361864/