How to validate email and email already exist or not check, in Yii Framework?
Asked Answered
A

6

16

How to validate email using Yii Model validation rules function code. Also how to check email exist or not using Model validation rules function in Yii.

Armidaarmiger answered 8/10, 2012 at 8:55 Comment(0)
S
25

You can set your model validations as below

public function rules()
{
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
            //First parameter is your field name of table which has email value
        array('email', 'email','message'=>"The email isn't correct"),
        array('email', 'unique','message'=>'Email already exists!'),            
    );
}

Yii Reference Link For More Detail: http://www.yiiframework.com/wiki/56/

Speculum answered 8/10, 2012 at 9:1 Comment(0)
L
6

You can create your custom validation method to fulfill your requirement.

Create a function in model class:

public function uniqueEmail($attribute, $params)
{
     // Set $emailExist variable true or false by using your custom query on checking in database table if email exist or not.
    // You can user $this->{$attribute} to get attribute value.

     $emailExist = true;

     if($emailExist)
    $this->addError('email','Email already exists');
}

User this validation method in rules:

array('email', 'uniqueEmail','message'=>'Email already exists!'),    
Leister answered 8/10, 2012 at 9:52 Comment(0)
R
5

Custom validation, short and sweet code. try this it's working fine -

public function rules(){   
        return array(
            array('email, first_name, last_name, password, repeat_password', 'required'),
            array('email', 'email','message'=>"The email isn't correct"),
            array('email', 'uniqueEmail'),
        );  
    }

write this custom function in the same model -

public function uniqueEmail($attribute, $params){
        if($user = User::model()->exists('email=:email',array('email'=>$this->email)))
          $this->addError($attribute, 'Email already exists!');
    }
Rosemarierosemary answered 17/7, 2014 at 11:23 Comment(1)
This will work for Yii2 as well if the test is simplified to: if (User::findOne(['email' => $this->email]))Etruscan
A
5

For Yii2 I used the following in a model called Register which will use the User Class.

public function rules()
{
    return [

        ['Email', 'filter', 'filter' => 'trim'],
        ['Email', 'required'],
        ['Email', 'email'],
        ['Email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],

    ];
}

You need to use targetClass and put the Namepsace for the Class User

Analogue answered 30/7, 2015 at 7:45 Comment(0)
W
3

You can easily find either email is already present in your db or not by defining the rule.

Here is the rule.

array('xxx', 'unique', 'className' => 'SomeClass', 'attributeName' => 'SomeAttribute'),

Example.

public function rules() {
   return array(
     ...
     array('email', 'unique', 'className' => 'User', 'attributeName' => 'email', 'message'=>'This Email is already in use'),
     ...
); 
}

Here i want to put validation on Email, which is unique, my model class name is User, attributeName is the field name of the table i.e. email and if email is already present in your table then display message.

If it gives error then you may change your table and make unique the email field.

ALTER TABLE user ADD UNIQUE (email)

Then check.

other email validations are in below. which i think complete set of email validation.

public function rules() {
   return array(
     ...
     array('email', 'required'), 
     array('email', 'length', 'max'=>200),
     array('email', 'email', 'message'=>'Email is not valid'),
     array('email', 'unique', 'className' => 'User', 'attributeName' => 'email', 'message'=>'This Email is already in use'),
     ...
); }

That's it. Thanks

Wurtz answered 4/11, 2013 at 7:47 Comment(0)
D
0

Follow the few modifications as below: Follow your file as per your module you have used.

Go to models -> open-> Users.php -> Modify line as mentioned below.

 public function rules()
    {
        return [
                [['User_Email'], 'unique'],
                [['User_Mobile'],'unique'],
              ];
     }

Now Go to views-> users ->Open _form.php-> write the code as mentioned below

<div class="users-form">

    <?php $form = ActiveForm::begin([
            'id' => $model->formName(),
            'enableAjaxValidation' => true,
        ]); ?>

 <?= $form->field($model, 'User_Email')->textInput(['maxlength' => true])?>
 <?= $form->field($model, 'User_Mobile')->textInput(['maxlength' => true])?>
    <div class="form-group">
            <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update',  ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
        </div>

        <?php ActiveForm::end(); ?>

    </div>

Now Go to Controller->open UsersController.php -> wirte the code as mentioned below

public function actionCreate()
    {
       if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())){
            Yii :: $app->response->format = 'json';
            return \yii\bootstrap\ActiveForm::validate($model);
            }
}

Thank you

Dancette answered 18/10, 2016 at 12:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.