简单的方法:在 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

转载于:https://www.cnblogs.com/DaBing0806/p/4744118.html

Yii自定义验证规则相关推荐

  1. yii2中的rules 自定义验证规则详解

    yii2的一个强大之处之一就是他的Form组件,既方便又安全.有些小伙伴感觉用yii一段时间了,好嘛,除了比tp"难懂"好像啥都没有. 领导安排搞一个注册的功能,这家伙刷刷刷的又是 ...

  2. 教你三种Model(AR)中自定义验证规则的方法

    2019独角兽企业重金招聘Python工程师标准>>> 各位Yii2兄弟都知道Model的rules里面可以使用自己定义的验证规则,我们今天就把自定义规则做一个总结,进行一次彻底的知 ...

  3. 后盾网lavarel视频项目---自定义验证和自定义验证规则

    后盾网lavarel视频项目---自定义验证和自定义验证规则 一.总结 一句话总结: 1.自定义验证就是用的自定义验证请求类:php artisan make:request AdminPost 2. ...

  4. easyui的validatebox重写自定义验证规则的几个实例

    validatebox已经实现的几个规则: 验证规则是根据使用需求和验证类型属性来定义的,这些规则已经实现(easyui API): email:匹配E-Mail的正则表达式规则. url:匹配URL ...

  5. validatebox自定义验证规则以及使用

    //===============jsp======state====//开启验证<script type="text/javascript"> ​​​​​​​yZ() ...

  6. php验证法则是10位数字,自定义验证规则

    > ## 设置验证规则 ``` // 1.数组传入(针对在控制器中定义验证) $rules = [ 'name' => 'require|max:25', 'age' => 'num ...

  7. layui单选框verify_layui lay-verify form表单自定义验证规则详解

    虽然layui的官方文档已经是写的比较详细,但是初次使用的时候总会懵一下,这里纪录一下lay-verify自定义验证规则的时候到底放哪. html: 提交 js: form.verify({ //数组 ...

  8. layui的表单——自定义验证规则

    最近layui的表单用的比较多,所以整理来一下自定义的验证如下(下面是自己写的例子): layui的官网 引入layui之后 html <form action="" cla ...

  9. Gin验证请求参数-自定义验证规则

    Gin对请求参数自定义验证规则可以分三步: 自定义结构体验证绑定binding标签 针对该标签定义验证方法 再将该验证方法注册到validator验证器里面 自定义结构体验证绑定binding标签 需 ...

最新文章

  1. ESP8266 问题
  2. 功能农业奠基人-农业大健康·万祥军:赵其国安康工作站揭牌
  3. 兼容超大图片的处理_计算机读取超大图像的一些问题简述
  4. sql 函数 汉字转拼音
  5. 用jekyll制作高大上的网站(二)——实际应用
  6. 配送交付时间轻量级预估实践
  7. mysql 安装是否成功,启动,查看配置文件,连接
  8. 数学建模matlab题型,数学建模题型之分类
  9. PHP 互联网架构师成长之路*「swoole」终极指南
  10. 手机上获取地图某个定位的经纬度坐标的方法 - 查询经度、纬度 - 百度地图app、高德地图app、Earth地球
  11. 用户画像、用户分群、用户分层,到底有啥区别?
  12. Springboot Swagger2 Unable to infer base url问题解决
  13. 闲时整理3--Android调用指纹验证
  14. vue-quill-editor编辑器踩坑
  15. 一些很漂亮的字符图片
  16. My sql 统计一个字段某种类型的总数(非group by)
  17. 面试蚂蚁金服(意外拿到offer)分享四面经历,从线程锁到数据库
  18. 华晨宏盛:只需建立正确的理财观,把握科学的理财办法
  19. Dvorak Simplified Keyboard
  20. Elasticsearch实战 | match_phrase搜不出来,怎么办?

热门文章

  1. 《超越想象——Windows_8应用设计与开发》
  2. [Erlang-0011][OTP] External Term Format
  3. Hadoop安装的ssh免密码登录步骤
  4. 我的第一个python web开发框架(3)——怎么开始?
  5. 第二冲刺站立会议01
  6. C语言写的俄罗斯方块
  7. Web Service学习笔记
  8. linux端口监听命令
  9. MapReduce提交作业常见问题
  10. Java语言编码规范