1.重写scenarios 可以不重写
1
2
3
4
5
6
7
| public function scenarios()
{
return array_merge(parent::scenarios(),[
'login'=>['adminuser','adminpass','rememberMe'],
'seekpass'=>['adminuser','adminemail']
]);
} |
public function scenarios()
{
return array_merge(parent::scenarios(),[
'login'=>['adminuser','adminpass','rememberMe'],
'seekpass'=>['adminuser','adminemail']
]);
}
2.为rules设置场景 不设置的默认使用全部
1
2
3
4
5
6
7
8
9
10
11
12
13
| public function rules()
{
return [
[['adminuser'],'required','message'=>'用户名不能为空','on'=>['login','seekpass']],
[['adminpass'],'required','message'=>'密码不能为空','on'=>'login'],
['rememberMe','boolean','on'=>'login'],
['adminpass','validatePass','on'=>'login'],
['adminemail','required','message'=>'邮箱必填','on'=>'seekpass'],
['adminemail','email','message'=>'邮箱格式不正确','on'=>'seekpass'],
['adminemail','validateEmail','on'=>'seekpass']
];
} |
public function rules()
{
return [
[['adminuser'],'required','message'=>'用户名不能为空','on'=>['login','seekpass']],
[['adminpass'],'required','message'=>'密码不能为空','on'=>'login'],
['rememberMe','boolean','on'=>'login'],
['adminpass','validatePass','on'=>'login'],
['adminemail','required','message'=>'邮箱必填','on'=>'seekpass'],
['adminemail','email','message'=>'邮箱格式不正确','on'=>'seekpass'],
['adminemail','validateEmail','on'=>'seekpass']
];
}
3.在 调用validate()前 指定使用的场景
1
2
3
4
5
6
7
8
| public function seekpass($data)
{
$this->setScenario('seekpass');
if($this->load($data) && $this->validate())
{
}
} |
public function seekpass($data)
{
$this->setScenario('seekpass');
if($this->load($data) && $this->validate())
{
}
}
未经允许不得转载:开心乐窝-乐在其中 » yii2场景验证