روش کامل - توسعه کلاس CValidator فریمورک:
این روش از اون جهت بهتره که میتونید به راحتی کلاس Validator خودتون رو در پروژه های دیگه هم بکار ببرین. برای اینکار، ابتدا توی پوشه 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,}$/';
/**
* 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!');
}
}
}
حالا توی متد rules توی مدلتون باید اینطوری بنویسید:
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
return array(
// ...
array('password', 'passwordStrength', 'strength'=>'strong'),
// ...
);
}
نکته: علت اینکه گفته شد یک پوشه به اسم MyValidators بسازین و فایل رو به اسم کلاس و با پسوند php. داخلش ذخیره کنید اینه که از قابلیت LazyLoading موجود در Yii استفاده بشه وگرنه میشد هرجایی بگذارین و توی فایل تنظیمات main.php تو قسمت import فایلهاش رو فراخوانی کنید.
نکته بعدی: اگه میخواین Validation سمت کلاینت رو هم بازنویسی کنید، باید یک متد دیگه به کلاستون اضافه کنید:
/**
* 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!') . '); }';
}