ajax - Yii2 ajax 和客户端验证不起作用

标签 ajax validation activerecord yii2

Ajax 验证未触发,需要帮助找出我的代码有什么问题,斗争花了足够长的时间让我在这里寻求帮助,所以请帮忙。有一些带注释的代码,在尝试使其工作时使用。收到 500 内部服务器错误:

{"name":"Exception","message":"Attribute name must contain word characters only."

用户 Controller

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,
    ]);
}

注册.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()
    {

最佳答案

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

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

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

关于ajax - Yii2 ajax 和客户端验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31059415/

相关文章:

javascript - 使用 ajax/javascript 选择项目并将其添加回 mysql

javascript - Firefox 49.0.2 附加组件的 XMLHttpRequest Status 0

ruby-on-rails - rails ActiveRecord 对特定 Controller 和 Action 的验证

ruby-on-rails - 检查记录是否刚刚在 rails 中被破坏

javascript - 从 mysql 到 javascript 变量

php - 实时用户名搜索不起作用。提交也停止工作

php - 用于匹配字母数字字符、下划线、句点和破折号的正则表达式,只允许在中间使用点和破折号

java - 使用 SAXParser 根据 XSD 验证 XML 结果错误

ruby-on-rails - 如何设置 Rails 验证列 hstore 键的唯一性?

javascript - Rails `link_to` 方法多次发布