Nectos
Nectos

Reputation: 206

Yii2 ajax and client side validation not working

Ajax validation is not triggered, need help finding what is wrong with my code, struggle took long enough to make me seek help here so please help. There is some commented code, that was used while trying to make it work. Getting 500 internal server error:

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

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()
    {

Upvotes: 2

Views: 9084

Answers (3)

MichaelMcD
MichaelMcD

Reputation: 31

I found that AJAX Validation required:

use yii\widgets\ActiveForm;

To be at the top of both the form and the controller.

Upvotes: 0

Kalpesh Desai
Kalpesh Desai

Reputation: 1421

Hey your code is fine but your mistake is that you provide two id for single form one is form-signsup and ajax. try using only one...:)

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

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

Upvotes: 3

avelasquez27
avelasquez27

Reputation: 1

In your register.php change the line:

And set it true, and that's it, hope it was helpful 'form-signsup',

                'enableAjaxValidation' => 'true',
                ]); ?>

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

Upvotes: 0

Related Questions