首页 > PHP资讯 > PHP培训技术 > yii-自定义验证规则

yii-自定义验证规则

PHP培训技术
自定义验证规则

很多时候 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 数组中.

你会发现在方法中我们使用了

PHP培训技术

本文由欣才IT学院整理发布,未经许可,禁止转载。
支持11不支持0