在action函数中,调用model中的validate函数
$model=new LoginForm;
$model->attributes=$_POST['LoginForm'];
if($model->validate() && $model->login())
$this->redirect(Yii::app()->user->returnUrl);
CModel::validate($attributes=null, $clearErrors=true)
{
$this->beforeValidate()
foreach($this->getValidators() as $validator)$validator->validate($this,$attributes);
$this->afterValidate();
}
CModel::getValidators()
$this->_validators=$this->createValidators();
public function createValidators()
{
$validators=new CList;
foreach($this->rules() as $rule) //从rule数组中读取规则
{
if(isset($rule[0],$rule[1])) // attributes, validator name
$validators->add(CValidator::createValidator($rule[1],$this,$rule[0],array_slice($rule,2)));
else
throw new CException(Yii::t('yii','{class} has an invalid validation rule. The rule must specify attributes to be validated and the validator name.',
array('{class}'=>get_class($this))));
}
return $validators;
}
CValidator::createValidator($rule[1],$this,$rule[0],array_slice($rule,2))//如果Model类中有这个函数名,则直接用Model类中的函数,否则,创建系统默认的类,如CRequiredValidator
{ if(method_exists($object,$name))
{
$validator=new CInlineValidator;
$validator->attributes=$attributes;
$validator->method=$name;
else
{
$params['attributes']=$attributes;
if(isset(self::$builtInValidators[$name]))
$className=Yii::import(self::$builtInValidators[$name],true);
else
$className=Yii::import($name,true);
$validator=new $className;
foreach($params as $name=>$value)
$validator->$name=$value;
}
}
CRequiredValidator::validateAttribute($object,$attribute) //最终调用对应的Validate类中的CValidator::validate函数调用子类的validateAttribute函数
{
$value=$object->$attribute;
if($this->requiredValue!==null)
{
if(!$this->strict && $value!=$this->requiredValue || $this->strict && $value!==$this->requiredValue)
{
$message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be {value}.',
array('{value}'=>$this->requiredValue));
$this->addError($object,$attribute,$message);
}
}
elseif($this->isEmpty($value,$this->trim))
{
$message=$this->message!==null?$this->message:Yii::t('yii','{attribute} cannot be blank.');
$this->addError($object,$attribute,$message);
}
}