我正在yii2中进行客户端验证,但它对我不起作用。
查看文件

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\captcha\Captcha;

?>

<ul class="breadcrumb">
    <li><a href="index.html">Home</a></li>
    <li><a href="#">Pages</a></li>
    <li class="active">Login</li>
</ul>
<!-- BEGIN SIDEBAR & CONTENT -->
<div class="row margin-bottom-40">
    <!-- BEGIN SIDEBAR -->
    <!--<div class="sidebar col-md-3 col-sm-3">
        <ul class="list-group margin-bottom-25 sidebar-menu">
            <li class="list-group-item clearfix"><a href="<?php /*echo Yii::$app->urlManager->createUrl('site/register'); */?>"><i class="fa fa-angle-right"></i> Register</a></li>
            <li class="list-group-item clearfix"><a href="#"><i class="fa fa-angle-right"></i> Restore Password</a></li>
            <li class="list-group-item clearfix"><a href="#"><i class="fa fa-angle-right"></i> My account</a></li>
            <li class="list-group-item clearfix"><a href="#"><i class="fa fa-angle-right"></i> Address book</a></li>
            <li class="list-group-item clearfix"><a href="#"><i class="fa fa-angle-right"></i> Wish list</a></li>
            <li class="list-group-item clearfix"><a href="#"><i class="fa fa-angle-right"></i> Returns</a></li>
            <li class="list-group-item clearfix"><a href="#"><i class="fa fa-angle-right"></i> Newsletter</a></li>
        </ul>
    </div>-->
    <!-- END SIDEBAR -->

    <!-- BEGIN CONTENT -->
    <div class="col-md-9 col-sm-9">
        <h1>Login</h1>
        <div class="content-form-page">
            <div class="row">
                <div class="col-md-7 col-sm-7">
                    <?php $form = ActiveForm::begin(['id' => 'login-form','class' => 'form-horizontal form-without-legend']); ?>
                    <?php echo $form->errorSummary($model); ?>
                        <div class="form-group">
                            <label for="email" class="col-lg-4 control-label">Email <span class="require">*</span></label>
                            <div class="col-lg-8">
                                <?= $form->field($model, 'username',['template' => "{input}"])->textInput(array('placeholder' => 'Username','class'=>'form-control validate[required]'));  ?>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="password" class="col-lg-4 control-label">Password <span class="require">*</span></label>
                            <div class="col-lg-8">
                                <?= $form->field($model, 'password',['template' => "{input}"])->passwordInput(array('class'=>'form-control validate[required]','placeholder'=>'Password')); ?>
                                <!--<input type="text" class="form-control" id="password">-->
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg-8 col-md-offset-4 padding-left-0">
                                <a href="#">Forget Password?</a>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg-8 col-md-offset-4 padding-left-0 padding-top-20">
                                <?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
                                <!--<button type="submit" class="btn btn-primary">Login</button>-->
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg-8 col-md-offset-4 padding-left-0 padding-top-10 padding-right-30">
                                <hr>
                                <div class="login-socio">
                                    <p class="text-muted">or login using:</p>
                                    <ul class="social-icons">
                                        <li><a href="#" data-original-title="facebook" class="facebook" title="facebook"></a></li>
                                        <li><a href="#" data-original-title="Twitter" class="twitter" title="Twitter"></a></li>
                                        <li><a href="#" data-original-title="Google Plus" class="googleplus" title="Google Plus"></a></li>
                                        <li><a href="#" data-original-title="Linkedin" class="linkedin" title="LinkedIn"></a></li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    <?php ActiveForm::end(); ?>
                    <!--</form>-->
                </div>
                <!--<div class="col-md-4 col-sm-4 pull-right">
                    <div class="form-info">
                        <h2><em>Important</em> Information</h2>
                        <p>Duis autem vel eum iriure at dolor vulputate velit esse vel molestie at dolore.</p>

                        <button type="button" class="btn btn-default">More details</button>
                    </div>
                </div>-->
            </div>
        </div>
    </div>
    <!-- END CONTENT -->
</div>
<!-- END SIDEBAR & CONTENT -->

列控制器文件
<?php
namespace frontend\controllers;


use frontend\models\Users;
use backend\models\SmsData;
use backend\models\SmsDataSearch;
use Yii;
use frontend\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\data\ArrayDataProvider;

/**
 * Site controller
 */
class SiteController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),

                'rules' => [

                    [
                        'actions' => ['login','index', 'error','register'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout','report','create','delete'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                   // 'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    public function actionIndex()
    {
            return $this->render('index');
    }

    public function actionRegister()
    {
         $model = new Users();

            if($model->load(Yii::$app->request->post()))
            {
                $model->status='0';
                $model->is_delete='0';
                $model->created_by='1';
                $model->password=md5($_POST['Users']['password']);
                $model->created_date=date('Y-m-d h:i:s');
                $model->role_type='1';

                $model->save();

               Yii::$app->session->setFlash('success', 'You Have Successfully Register');
               return $this->redirect(array('login'));
            }

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

    public function actionLogin()
    {
        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {

            $data=Yii::$app->db->createCommand("select * from `users` where user_id = '".Yii::$app->user->getId()."'")->queryAll();

            if($data[0]['role_type'] == '1')
            {
                Yii::$app->session->setFlash('success', 'You Have Successfully LogIn');
                return $this->redirect(array('report'));
            }
            elseif($data[0]['role_type'] =='0')
            {

                Yii::$app->session->setFlash('success', 'You Have Successfully LogIn');
                $url=Yii::$app->urlManager->createUrl('users/index');

                return $this->redirect($url);
            }

        } else {

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

    public function actionReport()
    {

        $model= new SmsData();

        if($model->load(Yii::$app->request->post()))
        {
            $fromdate=date('Y-m-d',strtotime($_POST['SmsData']['fromDate']));
            $todate = date('Y-m-d',strtotime($_POST['SmsData']['toDate']));

            $query="SELECT s.*,r.description as ratingtext FROM sms_data s
                    INNER JOIN users u ON u.unique_id = s.client_id
                    LEFT JOIN rating r ON r.rating = s.rating
                    WHERE u.user_id = '".Yii::$app->user->getId()."' AND s.message_id != '9999' AND date(s.created_date) >= '".$fromdate."' AND date(s.created_date) <= '".$todate."'";

            $data=Yii::$app->db->createCommand($query)->queryAll();

            $provider = new ArrayDataProvider([
                'allModels' => $data,

                'pagination' => [
                    'pageSize' => 10,
                ],
            ]);

            $model->fromDate=$_POST['SmsData']['fromDate'];
            $model->toDate=$_POST['SmsData']['toDate'];

            return $this->render('report',['dataProvider'=>$provider,'model'=>$model]);
        }
        else
        {
            $query="SELECT s.*,r.description as ratingtext FROM sms_data s
                    INNER JOIN users u ON u.unique_id = s.client_id
                    LEFT JOIN rating r ON r.rating = s.rating
                    WHERE u.user_id = '".Yii::$app->user->getId()."'  AND s.message_id != '9999' ";
            $data=Yii::$app->db->createCommand($query)->queryAll();


            $provider = new ArrayDataProvider([
                'allModels' => $data,

                'pagination' => [
                    'pageSize' => 10,
                ],
            ]);

            return $this->render('report',['dataProvider'=>$provider,'model'=>$model]);
        }


    }

    public function actionCreate()
    {
        $model = new SmsData();
        if($model->load(Yii::$app->request->post())) {

            $clientID=\frontend\models\Users::findOne(Yii::$app->user->getId());

            $model->created_by = Yii::$app->user->getId();
            $model->created_date= date('Y-m-d',strtotime($_POST['SmsData']['created_date']));
            $model->rating = $_POST['SmsData']['rating'];
            $model->text = $_POST['SmsData']['text'];
            $model->message_id = 9999;
            $model->client_id = $clientID->unique_id;

            $model->save();

            Yii::$app->session->setFlash('success', 'Data Inserted Successfully');
            return $this->redirect(array('create'));
        } else {

            $query="SELECT s.*,r.description as ratingtext FROM sms_data s
                    INNER JOIN users u ON u.unique_id = s.client_id
                    LEFT JOIN rating r ON r.rating = s.rating
                    WHERE u.user_id = '".Yii::$app->user->getId()."' AND message_id = 9999
                    AND s.is_delete = 0 AND s.status = 1";
            $data=Yii::$app->db->createCommand($query)->queryAll();

            $provider = new ArrayDataProvider([
                'allModels' => $data,
                'pagination' => [
                    'pageSize' => 10,
                ],
            ]);


            return $this->render('create',['model'=>$model,'dataProvider'=>$provider]);
        }
    }

    public function actionDelete($id) {
        $model = new SmsData();
        $command = Yii::$app->db->createCommand('UPDATE sms_data SET is_delete = 1 WHERE sms_id='.$id);
        $command->execute();
        Yii::$app->session->setFlash('success', 'Deleted Successfully ');
        return $this->redirect(array('create'));
    }

    public function actionLogout()
    {
        Yii::$app->user->logout();
        Yii::$app->session->setFlash('success', 'You Have Successfully Logout');
        return $this->goHome();
    }

    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
                Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
            } else {
                Yii::$app->session->setFlash('error', 'There was an error sending email.');
            }

            return $this->refresh();
        } else {
            return $this->render('contact', [
                'model' => $model,
            ]);
        }
    }

    public function actionAbout()
    {
        return $this->render('about');
    }

    public function actionSignup()
    {
        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                if (Yii::$app->getUser()->login($user)) {
                    return $this->goHome();
                }
            }
        }

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

    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->getSession()->setFlash('success', 'Check your email for further instructions.');

                return $this->goHome();
            } else {
                Yii::$app->getSession()->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
            }
        }

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

    public function actionResetPassword($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->getSession()->setFlash('success', 'New password was saved.');

            return $this->goHome();
        }

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


}

模型:
<?php
namespace frontend\models;

use frontend\models\Users;
use Yii;
use yii\base\Model;

/**
 * Login form
 */
class LoginForm extends Model
{
    public $username;
    public $password;
    public $rememberMe = true;
    private $_user = false;
    private $_id = false;
    private $_name;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['username', 'password'], 'required'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     */
    public function validatePassword()
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError('password', 'Incorrect username or password.');
            }

        }
    }

    /**
     * Logs in a user using the provided username and password.
     *
     * @return boolean whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
        } else {
            return false;
        }
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = Users::findByUsername($this->username);
        }

        return $this->_user;
    }

    public function getId()
    {
        if ($this->_id === false) {
            $this->_id = $this->user_id;
        }

        return $this->_id;
    }


}

我需要做什么来进行客户端验证?服务器端验证对我有效。

最佳答案

这不是虫子!必须使用activeform::validate()将错误发送回浏览器,因为它将属性格式化为与activeform呈现相同的格式

if (Yii::$app->request->isAjax && $model->load($_POST))
{
Yii::$app->response->format = 'json';
return \yii\widgets\ActiveForm::validate($model);
}

关于php - 客户端验证无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27560892/

10-10 14:46