Yii2 ajax和客户端验证无法正常工作

时间:2015-06-25 19:43:34

标签: ajax validation activerecord yii2

没有触发Ajax验证,需要帮助查找我的代码有什么问题,奋斗需要很长时间才能让我在这里寻求帮助所以请帮助。有一些注释代码,在尝试使其工作时使用。获取500内部服务器错误:

  

{“name”:“Exception”,“message”:“属性名称必须包含单词   只有字符。“

UserController中

public function actionRegister()
{        
    $model = new Users();
    if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
        $model->scenario = 'ajax';
        Yii::$app->response->format = Response::FORMAT_JSON;
        Yii::error($model);
        $model->validate();
        return ActiveForm::validate($model);
        //both ways not working the way it should
        //return $model->validate();
    }     
    if ($model->load(Yii::$app->request->post())) {
        if ($user = $model->register()) {                
            if (Yii::$app->getUser()->login($user)) {
                return $this->goHome();
            }
        }
    }
    return $this->render('register', [
        'model' => $model,
    ]);
}

register.php

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;

            <?php $form = ActiveForm::begin(['id' => 'form-signsup',

                    'enableAjaxValidation' => false,
                    'enableClientValidation' => true,
                    'id' => 'ajax'
                    ]); ?>

                <?= $form->field($model, 'UserName') ?>
                <?= $form->field($model, 'Name', ['enableAjaxValidation' => true]) ?>
                <?= $form->field($model, 'LastName', ['enableAjaxValidation' => true]) ?>
                <?= $form->field($model, 'Email') ?>
                <?= $form->field($model, 'PasswordHash', ['enableAjaxValidation' => true])->passwordInput() ?>
                <?= $form->field($model, 'repeatPassword', ['enableAjaxValidation' => true])->passwordInput() ?>
                    <?= Html::submitButton('Register', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?> 

Users.php

<?php

namespace app\models;

use Yii;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\base\Model;
use yii\web\Response;
use yii\widgets\ActiveForm;
class Users extends ActiveRecord implements IdentityInterface
{
public $rememberMe;
public $repeatPassword;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'users';
    }
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['UserName', 'PasswordHash', 'Name', 'LastName', 'Email'], 'required'],
            [['Name', 'LastName'], 'validateLetters', 'skipOnError' => false, 'on'=>'ajax'],
            [['repeatPassword'], 'validatePasswordRepeat', 'skipOnEmpty' => false, 'on'=>'ajax'],
            [['IsEnabled'], 'boolean'],
            [['rememberMe'], 'boolean'],
            [['UserName', 'Name', 'LastName'], 'string', 'max' => 50],
            [['Email'], 'email', 'message'=>'Netinkamai įvestas el. paštas.'],
            [['PasswordHash', 'repeatPassword' ], 'string', 'max' => 20],
            [['Email'], 'string', 'max' => 80]
        ];
    }

    public function scenarios()
    {
        $scenarios = parent::scenarios();
        $scenarios['ajax'] = ['Name', 'LastName', 'repeatPassword', 'PasswordHash'];//Scenario Values Only Accepted
        //$scenarios['default'] = ['Name','LastName', 'passwordRepeat', 'PasswordHash', 'Email'];
        return $scenarios;
        // return [
        //     ['some_scenario' => ['UserName', 'PasswordHash', 'Name', 'LastName', 'Email', 'IsEnabled']],
        // ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'Id' => 'ID',
            'UserName' => 'Prisijungimo vardas',
            'PasswordHash' => 'Slaptažodis',
            'Name' => 'Vardas',
            'LastName' => 'Pavardė',
            'Email' => 'El. paštas',
            'IsEnabled' => 'Is Enabled',
            'rememberMe' => 'Prisiminti?',
            'AuthKey' => 'Authentication key',
            'repeatPassword' => 'Pakartoti slaptažodį',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUserRoles()
    {
        return $this->hasMany(UserRole::className(), ['User_ID' => 'Id']);
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePasswordRepeat($attribute)
    {

        //if(!($this->$attribute == $this->PasswordHash)){
       // $this->clearErrors();
           $this->addError($this->repeatPassword, 'Slaptažodis nesutampa.');
           return $this->addError($this->repeatPassword, 'Slaptažodis nesutampa.');
       // }
//$this->addError($attribute, 'Slaptažodis nesutampa.');
       // return Yii::$app->security->validatePassword($attribute, $this->PasswordHash);
        //return Yii::$app->security->validatePassword($attribute, $this->PasswordHash);
    }

    /**
     * Validates name / last name string so it has no numbers or random symbols
     *
     * @param string $password password to validate
     * @return boolean if password provided is valid for current user
     */

    public function validateLetters($attribute)
    {

        Yii::error($attribute);Yii::error($this->$attribute);
        if(!preg_match('/^[a-zA-ZąčęėįšųūžĄČĘĖĮŠŲŪŽ]+$/', $this->$attribute)){
            $this->addError($attribute, 'Galima naudoti tik raides.');
        }

    }

    public function register()
    {

        if ($this->validate()) {
            $user = new Users();

            $user->UserName = $this->UserName;
            $user->Email = $this->Email;
            $user->Name = $this->Name;
            $user->LastName = $this->LastName;
            $user->setPassword($this->PasswordHash);

            if ($user->save()) {               
                return $user;
            }
        }

     //   var_dump($user->getErrors()); die();
    }

    public function login()
    {
            // $user = $this->getUser();
            //var_dump($user);
            //echo "----------------------";
        //$this->PasswordHash = md5($this->PasswordHash);
            //var_dump($this->PasswordHash);
           // die();
        // if ($this->validate()) {
        //     $this->PasswordHash = md5($this->PasswordHash);
        //     return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
        // } else {
        //     return false;
        // }

        if ($this->validate()) {
            //die();
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
        } else {
            return false;
        }
    }
        /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($UserName)
    {
        return static::findOne(['UserName' => $UserName]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return boolean
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        $parts = explode('_', $token);
        $timestamp = (int) end($parts);
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->AuthKey;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }



    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->PasswordHash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->AuthKey = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {

3 个答案:

答案 0 :(得分:2)

嘿,你的代码很好,但你的错误是你为单一形式提供了两个id,一个是form-signsup和ajax。尝试只使用一个......:)

<?php $form = ActiveForm::begin(['id' => 'form-signsup',

                    'enableAjaxValidation' => false,
                    'enableClientValidation' => true,
                    //'id' => 'ajax'
                    ]); ?>

答案 1 :(得分:0)

在您的register.php中更改以下行:

并将其设置为true,就是这样,希望它有用'form-signsup',

func collectionView(collectionView:cellForItemAtIndexPath:) -> UICollectionViewCell

答案 2 :(得分:0)

我发现需要AJAX验证:

使用yii \ widgets \ ActiveForm;

同时位于表单和控制器的顶部。