newbrant newbrant - 1 year ago 279
PHP Question

Yii2: $model->validate() is not working

I wanna create my own login method, but firstly I may try to work with validation and then redirect to the page; however, the validate() method is not working.
Here is my code.

namespace backend\controllers;

use yii\web\Controller;
use common\models\LoginForm;
use Yii;

class LoginController extends Controller{

public $layout = 'login' ;

public function actionIndex(){

$model = new LoginForm();

if($model->load(Yii::$app->request->post() && $model->validate())){
return $this->redirect(['site/index']);
echo "<br>";
echo "To be continued...";

return $this->render('index',['model' => $model]);


Here it is the LoginForm.php:

namespace common\models;

use Yii;
use yii\base\Model;
use common\models\User;

class LoginForm extends Model{

public $username;
public $password;
public $rememberMe = true;
public $verification;

public function rules(){
return [
[['username','password'],'required','message'=>'{attribute}Write Something...'],
//['password', 'validatePassword'],
/*Continue later after redirect works
public function validateUser($attribute,$params){
$user = User::findOne(['username'=>$this->$attribute]);
if(!$user || (md5($this->password) != $user['password'])){
$this->addError($this->attribute,'Errors Here...');


And here is my login/index.php

use yii\helpers\Html;
use Yii;



<div class="container">

<h2 class="form-signin-heading">Please sign in</h2>


<?=Html::activeInput('password', $model,'password',['id'=>'inputPassword','class'=>'form-control','placeholder'=>'Password'])?>
<div class="checkbox">
<input type="checkbox" value="remember-me"> Remember me
<?=Html::submitButton('Login',['class'=>'btn btn-lg btn-primary btn-block'])?>

So, the issues are:

    1. While accessing and validating the user input, no matter what I type,
      the Error would show up, either Blank or Filled with values.

    1. If I remove the $model->validate() from Controller, page will redirect to the index, but it is without validation.

    1. If I comment the username validation on the rules, just check for required, error would show the same. Input or blank will display
      error message that "Write Something".

Not sure where I did wrong, any helps would appreciated.

Answer Source

Looks like you just have a syntax mistake here:

if($model->load(Yii::$app->request->post() && $model->validate())){

Change it to

if($model->load(Yii::$app->request->post()) && $model->validate()){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download