在一个web应用中,可能有多个地方需要进行验证。比如“注册"时username、email、password这三项必须要填写,但是在“找回密码”时,可能只有email需要。所以,在Yii框架中,如果将这三项都设置为"required"那肯定是不可取的。
最好的解决办法莫过于建立不同的验证场景,通过"on"将一个场景与相应的规则相关联。来看一个User Model中rules()的例子:
public function rules() {
return array(
//Set required fields
//Applies to 'register' scenario
//Note 'on' property
array('username, password, password_repeat, email', 'required', 'on' => 'register'),
//Applies to 'recover' scenario
array('email', 'required', 'on' => 'recover'),
//Applies to all scenarios
array('username, password', 'length', 'max'=>35, 'min'=>3),
//This rule checks if the username is unique in the database in
//the 'register' scenario (we don't want it to check for uniqueness
//on the login page for instance)
array('username', 'unique', 'on' => 'register'),
//This rule applies to 'register' and 'update' scenarios
//Compares 'password' field to 'password_repeat' to make sure they are the same
array('password', 'compare', 'on' => 'register, update'),
);
}
通过注释我们能很好地理解这样定义的好处。现在我们可以通过调用CModel::validate()方法来为不同的场景进行验证:
if ($user->validate('register')) {
$user->save(false);
}