Yii CModel:hasErrors方法
CModel::hasErrors方法,竟然在authenticate时也能用,不是应该在所有的rules都验证完之后才能获取吗?后来经过测试和查看源码,才知道,hasError并不是一并获取,而是根据当前已经验证过的rule实时获取,也就是说,假如有a,b,c,d四条rule,那么如果crule需要一个回调函数去验证(如array('password', 'authenticate')),而且drule一定会验证出错误,那在authenticate方法中,是获取不到第d条rule验出的错误的.在回调函数中调用CModel:hasErrors时,一定要注意这一点
class LoginForm extends CFormModel{ .............. public function rules() { return array( // username and password are required array('username, password', 'required'), array('password', 'length', 'min'=>6), // rememberMe needs to be a boolean array('rememberMe', 'boolean'), // password needs to be authenticated array('password', 'authenticate'), ); } /** * Authenticates the password. * This is the 'authenticate' validator as declared in rules(). */ public function authenticate($attribute,$params) { if(!$this->hasErrors()) { $this->_identity=new UserIdentity($this->username,$this->password); if(!$this->_identity->authenticate()) $this->addError('password','邮箱或密码错误.'); } }