/**
* 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 在规则中自定义的参数
/**
* 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 的条件中使用常量,我推荐使用.
/**
* 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.