【发布时间】:2016-08-10 18:22:35
【问题描述】:
我想创建自己的登录方法,但首先我可能会尝试使用验证,然后重定向到页面;但是, validate() 方法不起作用。 这是我的代码。 登录控制器:
<?php
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']);
}else{
var_dump(Yii::$app->request->isPost);
echo "<br>";
var_dump($model->load(Yii::$app->request->post()));
echo "To be continued...";
}
return $this->render('index',['model' => $model]);
}
}
这里是 LoginForm.php:
<?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...'],
['username','validateUser'],
//['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...');
}
}
*/
这是我的登录名/index.php
<?php
use yii\helpers\Html;
use Yii;
//http://www.yiiframework.com/doc-2.0/guide-output-client-scripts.html
$this->registerCssFile('@web/css/bslogin.css');
?>
<div class="container">
<?=Html::beginForm('','post',['class'=>'form-signin'])?>
<h2 class="form-signin-heading">Please sign in</h2>
<?=Html::activeInput('text',$model,'username',['id'=>'username','class'=>'form-control','placeholder'=>'Username','autofocus'=>true])?>
<?=Html::error($model,'username')?>
<?=Html::activeInput('password', $model,'password',['id'=>'inputPassword','class'=>'form-control','placeholder'=>'Password'])?>
<?=Html::error($model,'password')?>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<?=Html::submitButton('Login',['class'=>'btn btn-lg btn-primary btn-block'])?>
<?=Html::endForm()?>
</div>
所以,问题是:
- 在访问和验证用户输入时,无论我输入什么, 将显示错误,无论是空白还是填充值。
- 如果我从 Controller 中删除 $model->validate(),页面将重定向到索引,但没有验证。
- 如果我在规则上评论用户名验证,只需检查是否需要,错误将显示相同。输入或空白将显示 “写东西”的错误消息。
不知道我哪里做错了,任何帮助将不胜感激。
【问题讨论】:
标签: php validation yii2