How to validate email and email already exist or n

2019-01-26 04:18发布

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.

6条回答
唯我独甜
2楼-- · 2019-01-26 04:50

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

查看更多
相关推荐>>
3楼-- · 2019-01-26 04:53

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!'),    
查看更多
祖国的老花朵
4楼-- · 2019-01-26 04:57

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

查看更多
Lonely孤独者°
5楼-- · 2019-01-26 04:58

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/

查看更多
等我变得足够好
6楼-- · 2019-01-26 04:58

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

查看更多
爷、活的狠高调
7楼-- · 2019-01-26 05:11

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!');
    }
查看更多
登录 后发表回答