模型中,一定要有验证码那一行
/**
* @return array the validation rules.
*/
public function rules()
{
return [
[['mobile', 'verifyCode'], 'required', 'on' => 'mobile'],
[['mobile', 'password', 'password1', 'smsCode'], 'required', 'on' => 'password'],
[['smsCode', 'password', 'password1'], 'string'],
**[ 'verifyCode', 'captcha'],**// 这里的'captcha'是系统的关键字,不能写成其他
['password', 'compare', 'compareAttribute' => 'password1'],
];
}
控制器中:
public function actions(){
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',// 这里用的是完全路径,如果用简写,上面要use这个命名空间
'fixedVerifyCode' => substr(rand(1000,9999), 0),
'height' => 50,
'width' => 100,
'maxLength' => 4,
'minLength' => 4,
],
];
}
视图中:
<?= $form->field($loginForm, 'verifyCode')->widget(Captcha::className(), ['imageOptions' => ['class' => "captcha"]]) ?>