Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

mysql - Display validation errors without page refresh

Is there any way I can just display validation errors in Yii2 without a redirect or refresh?

This is my default controller code performing the login action, I would like to highlight the text fields when the data entered does not match the data in the database, a simple validation against the database.

public function actionLogin()
    {
        /** @var amnahyii2usermodelsformsLoginForm $model */
        $model = $this->module->model("LoginForm");
    
        // load post data and login
        $post = Yii::$app->request->post();
        if ($model->load($post) && $model->validate()) {
            $returnUrl = $this->performLogin(
                $model->getUser(), $model->rememberMe
            );
            return $this->redirect($returnUrl);
        }
        
        return $this->render('login', compact("model"));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do it this way:

form login

<?php $form = ActiveForm::begin([
                            'validationUrl' => Url::toRoute(['site/login-validate']),
                            'action' => Url::toRoute(['site/login']),
                            'options' => [
                                    'class' => 'form login'
                            ],
                    ]); ?>

Site Controller

public function actionLoginValidate(){
      if(Yii::$app->request->isAjax){
            $model = new Login();
            if($model->load(Yii::$app->request->post())){
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }
      }
     throw new BadRequestHttpException("This action is not allowed.");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...