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)里面添加了表单,在表单被提交之前程序都会自动先来这里面的规则里验证,只有通过对其有效的限制规 ...
随机推荐
- BNU44583——Star Trek: First Contact——————【01背包】
H. Star Trek: First Contact Time Limit: 1000ms Memory Limit: 65536KB 64-bit integer IO format: %lld ...
- js验证护照号码是否合规
需求:最近要做实名验证的功能,但是验证我们要验证严谨一点,参考了网上关于验证护照号码的代码,总结一下. 代码: //验证护照号码 function checkPassport(code){ var t ...
- SQL Server 2008中的MERGE(数据同步)
OK,就像标题呈现的一样,SQL Server 2008中的MERGE语句能做很多事情,它的功能是根据源表对目标表执行插入.更新或删除操作.最典型的应用就是进行两个表的同步. 下面通过一个简单示例来演 ...
- 《Maven实战》关联实际工作的核心知识
通读了<Maven实战>这本书,由于在实际的工作中,对其有一定的操作上的经验.因此,再回头去通读这本书,就能够更加精准的把握里面的核心知识了. 以下我主要从两点去介绍之—— 1> m ...
- js控制input text字符键入/字符长度限制/字母自动大写
功能: 1.仅允许指定字符键入 2.限制长度 实现代码: <input type="text" style="width: 6em" name=" ...
- python的爬虫
requests库的安装 https://blog.csdn.net/xiaokuang5020/article/details/80580631 Response对象属性 属性 说明 r.statu ...
- JavaScript AMD 与CMD的代码区别
1:CMD 依赖就近 define(function(require,export) { var b =1; var a = require("../a"); a.dosometh ...
- sql server query to get the list of column name in a table
--SQL Server 2005, 2008 or 2012: SELECT * FROM information_schema.tables --SQL Server 2000: SELECT * ...
- 快速数组对象取值与数组映射新数组--array.map
array.map(callback,[ thisObject]); 1.map方法的作用不难理解,“映射”嘛,也就是原数组被“映射”成对应新数组 a)array.map(()=>值); [1, ...
- C# 修改GroupBox的边框颜色和字体颜色
改变GroupBox边框和的颜色 private void groupBox_BasicInformation_Paint(object sender, PaintEventArgs e) { e.G ...