Yii自定义验证规则
简单的方法:在 model 内部定义规则
最简单的定义验证规则的方法是在使用它的模型(model)内部定义。
比方说,你要检查用户的密码是否足够安全.
通常情况下你会使用 CRegularExpression 方法验证,但为了本指南,我们假设不存在此验证方法.
首先在模型(model)中添加两个常量
const WEAK = 0;
const STRONG = 1;
然后在模型(model)的 rules 方法中设置:
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
return array(
array('password', 'passwordStrength', 'strength'=>self::STRONG),
);
}
确保你写的规则不是一个已经存在的规则,否则将会报错.
现在要做的是在模型(model)中创建一个名称为上面填写的规则的方法(即 passwordStrength)。
/**
* check if the user password is strong enough
* check the password against the pattern requested
* by the strength parameter
* This is the 'passwordStrength' validator as declared in rules().
*/
public function passwordStrength($attribute,$params)
{
if ($params['strength'] === self::WEAK)
$pattern = '/^(?=.*[a-zA-Z0-9]).{5,}$/';
elseif ($params['strength'] === self::STRONG)
$pattern = '/^(?=.*\d(?=.*\d))(?=.*[a-zA-Z](?=.*[a-zA-Z])).{5,}$/';
if(!preg_match($pattern, $this->$attribute))
$this->addError($attribute, 'your password is not strong enough!');
}
刚才创建的方法需要两个参数:* $attribute 需要验证的属性* $params 在规则中自定义的参数
在模型的 rules 方法中我们验证的是 password 属性,所以在验证规则中需要验证的属性值应该是 password.
在 rules 方法中我们还设置了自定义的参数 strength,它的值将会放到 $params 数组中.
你会发现在方法中我们使用了 CModel::addError().
添加错误接受两个参数:第一个参数是在表单中显示错误的属性名,第二个参数时显示的错误信息 。
完整的方法:继承 CValidator 类
如果你想把规则使用在多个模型(model)中,最好的方法时继承 CValidator 类。
继承这个类你可以使用像 CActiveForm::$enableClientValidation (Yii 1.1.7 版本后可用) 类似的其他功能。
创建类文件
首先要做的是创建类文件.最好的方法时类的文件名和类名相同,可以使用 yii 的延迟加载(lazy loading)功能。
让我们在应用(application)的扩展(extensiions)目录(在 protected 文件夹下)下新建一个文件夹.
将目录命名为: MyValidators
然后创建文件: passwordStrength.php
在文件中创建我们的验证方法
class passwordStrength extends CValidator
{
public $strength;
private $weak_pattern = '/^(?=.*[a-zA-Z0-9]).{5,}$/';
private $strong_pattern = '/^(?=.*\d(?=.*\d))(?=.*[a-zA-Z](?=.*[a-zA-Z])).{5,}$/';
...
}
在类中创建属性,此属性为在验证规则中使用的参数.
CValidator 会自动根据参数来填充这些属性.
我们也创建了两个其他的属性,它们为 preg_match 函数使用的正则表达式.
现在我们应该重写父类的抽象方法(abstract method) validateAttribute
/**
* Validates the attribute of the object.
* If there is any error, the error message is added to the object.
* @param CModel $object the object being validated
* @param string $attribute the attribute being validated
*/
protected function validateAttribute($object,$attribute)
{
// check the strength parameter used in the validation rule of our model
if ($this->strength == 'weak')
$pattern = $this->weak_pattern;
elseif ($this->strength == 'strong')
$pattern = $this->strong_pattern;
// extract the attribute value from it's model object
$value=$object->$attribute;
if(!preg_match($pattern, $value))
{
$this->addError($object,$attribute,'your password is too weak!');
}
}
上面的方法我认为就不用解释了.当然你也可以在 if 的条件中使用常量,我推荐使用.
实现客户端验证
如果要实现客户端验证还需要重写类中的方法 clientValidateAttribute.
/**
* Returns the JavaScript needed for performing client-side validation.
* @param CModel $object the data object being validated
* @param string $attribute the name of the attribute to be validated.
* @return string the client-side validation script.
* @see CActiveForm::enableClientValidation
*/
public function clientValidateAttribute($object,$attribute)
{
// check the strength parameter used in the validation rule of our model
if ($this->strength == 'weak')
$pattern = $this->weak_pattern;
elseif ($this->strength == 'strong')
$pattern = $this->strong_pattern;
$condition="!value.match({$pattern})";
return "
if(".$condition.") {
messages.push(".CJSON::encode('your password is too weak, you fool!').");
}
";
}
正如你看到的此方法简单的返回了一个在验证中将使用到的 javascript.
最后一步:在模块(model)中怎么使用自定义的验证类
下面有几种方法来实现:
你可以在返回 规则数组(ruels array)前 使用 Yii::import 方法,或使用Yii的符号方式:
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
return array(
array('password', 'ext.MyValidators.passwordStrength', 'strength'=>self::STRONG),
);
}
参考:
HDR
Yii自定义验证规则的更多相关文章
- yii2中自定义验证规则rules
作者:白狼 出处:www.manks.top/article/yii2_custom_rules 本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追 ...
- yii2中的rules 自定义验证规则详解
yii2的一个强大之处之一就是他的Form组件,既方便又安全.有些小伙伴感觉用yii一段时间了,好嘛,除了比tp"难懂"好像啥都没有. 领导安排搞一个注册的功能,这家伙刷刷刷的又是 ...
- easyui的validatebox重写自定义验证规则的几个实例
validatebox已经实现的几个规则: 验证规则是根据使用需求和验证类型属性来定义的,这些规则已经实现(easyui API): email:匹配E-Mail的正则表达式规则. url:匹配URL ...
- thinkPHP5.0验证器自定义验证规则
自定义验证规则 protected $rule = [ 'views' => 'require|number|checkviews:0',//checkviews为自定义验证规则,0是传过去的规 ...
- Jquery Validate 相关参数及常用的自定义验证规则
一.官网地址:http://bassistance.de/jquery-plugins/jquery-plugin-validation 二.默认校验规则 1 2 3 4 5 6 7 8 9 10 1 ...
- validatebox自定义验证规则以及使用
//===============jsp======state==== //开启验证 <script type="text/javascript"> y ...
- Django【第16篇】:Django之Form组件自定义验证规则
自定义验证规则以及中间件简单介绍 1.python2和python3中的区别 对于python2内置的字符串类型有str和unicode 比如:"abc"是字符串,u"你 ...
- Jquery Validate自定义验证规则,一个汉字等于两个字符长度
使用Jquery validate时写的一些东西,在这里做个笔记 在使用 Jquery validate 的minlength和maxlength进行文本框内容长度验证的时候,对于一个汉字的长度检测结 ...
- YII开发技巧分享——模型(models)中rules自定义验证规则
YII的models中的rules部分是一些表单的验证规则,对于表单验证十分有用,在相应的视图(views)里面添加了表单,在表单被提交之前程序都会自动先来这里面的规则里验证,只有通过对其有效的限制规 ...
随机推荐
- POj2387——Til the Cows Come Home——————【最短路】
A - Til the Cows Come Home Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d & ...
- Firebird execute block 批处理
火鸟的批处理,效率好高,使用简单. execute block as declare variable i ; begin ) do begin :i = :i + ; insert into m_u ...
- Linux定时任务crontab使用指南
crontab命令被用来提交和管理用户的需要周期性执行的任务,与windows下的计划任务类似,当安装完成操作系统后,默认会安装此服务工具,并且会自动启动crond进程,crond进程每分钟会定期检查 ...
- 实现easyui的combogrid模糊查询框
这里用的方法是一个不可编辑的combogrid控件,覆盖上一个可输入的Input控件. 思路: 1.初始时取到后台查询出的列表,存储到全局变量 2.当输入框输入内容时,循环匹配列表,重新绑定到comb ...
- golang学习之select用法
早期的select函数是用来监控一系列的文件句柄,一旦其中一个文件句柄发生IO操作,该select调用就会被返回.golang在语言级别直接支持select,用于处理异步IO问题. select用法同 ...
- 网站部署中遇到的问题-未能加载文件或程序集“System.Data.SQLite”或它的某一个依赖项
问题描述: 运行站点抛出错误:未能加载文件或程序集“System.Data.SQLite”或它的某一个依赖项 原因: 应用程序池没有启用32位程序. 解决方法: 找到站点对应的应用程序池,设置启用32 ...
- Springmvc file多附件上传 显示 删除操作
之前项目需求要做一个多附件上传 并显示上传文件 带删除操作 一筹莫展之际搜到某个兄弟发的博客感觉非常好用被我copy下来了此贴算是改良版 再次感谢(忘记叫什么了时间也有点久没有历史记录了)先上图 基于 ...
- dubbo配置清单-超详细版
服务发布者 在服务发布者的springboot主配置文件application.properties中添加dubbo配置 #dubbo服务名 spring.dubbo.application.name ...
- Java使用反射来获取成员变量泛型信息
Java通过指定类对应的Class对象,程序可以获得该类里包括的所有Field,不管该Field使用private修饰,还是使用public修饰.获得了Field对象后,就可以很容易的获得该Field ...
- eclipse Java类 红色感叹号 commit失败
解决方法: 1.进入java类文件所在物理目录 (e:\workspace\myproject\...) 2. 删除多余的版本管理工具的文件或文件夹(如 .svn) 3. 刷新eclipse工程 4 ...