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)里面添加了表单,在表单被提交之前程序都会自动先来这里面的规则里验证,只有通过对其有效的限制规 ...
随机推荐
- 设置 mysql允许外网访问
mysql的root账户,我在连接时通常用的是localhost或127.0.0.1,公司的测试服务器上的mysql也是localhost所以我想访问无法访问,测试暂停. 解决方法如下: 1,修改表, ...
- hihocoder #1529 : 不上升序列
Description 给定一个长度为 n 的非负整数序列 a[1..n]. 你每次可以花费 1 的代价给某个 a[i] 加1或者减1. 求最少需要多少代价能将这个序列变成一个不上升序列. Solut ...
- 问题集录03--jquery解析json
先明确2个概念例如: JSON字符串: var str1 = '{ "name": "deyuyi", "sex": "man&q ...
- css内容简介(层叠样式表)
css是对网页编辑的加色,是对其功能的渲染. 根据规范每个元素都有一个display属性,每个元素都有一个------------如div元素他的默认为block. 行内元素和块级元素 块级元素会占据 ...
- mybatis mapper调用mysql存储过程
mybatis版本:3.4.4 存储过程 1.mapper.xml文件中配置相关的sql语句. <select id="callTest" statementType=&qu ...
- No.4一步步学习vuejs之表单输入绑定
基础用法 你可以用 v-model 指令在表单控件元素上创建双向数据绑定.它会根据控件类型自动选取正确的方法来更新元素.尽管有些神奇,但 v-model 本质上不过是语法糖,它负责监听用户的输入事件以 ...
- 用c+libcurl+PCRE写爬虫1--编译libcurl
打算用c语言和libcurl库在windows下实现一些爬虫操作. 一.编译libcurl 1.编译zlib 1)下载zlib http://sourceforge.net/projects/libp ...
- RabbitMQ如何解决各种情况下丢数据的问题
1.生产者丢数据 生产者的消息没有投递到MQ中怎么办?从生产者弄丢数据这个角度来看,RabbitMQ提供transaction和confirm模式来确保生产者不丢消息. transaction机制就是 ...
- Tomcat服务器配置和使用(三)
https连接器 明白了互联网上的加密原理之后,下面来看看浏览器与服务器交互时,浏览器想将数据加密后再发送给服务器,那么该怎么做呢?服务器首先要向浏览器出示一份数字证书,浏览器看到数字证书后,就可以使 ...
- Effective C++ .14 智能指针的拷贝与deleter函数
#include <iostream> #include <cstdlib> #include <memory> using namespace std; clas ...