php 在 Yii 框架中,如何验证电子邮件和电子邮件已存在或不检查?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12778326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:12:43  来源:igfitidea点击:

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

phpyiimodelyii-extensionsyii-components

提问by george

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.

如何使用 Yii 模型验证规则功能代码验证电子邮件。还有如何使用 Yii 中的模型验证规则功能检查电子邮件是否存在。

回答by GBD

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/

Yii 参考链接了解更多详情:http: //www.yiiframework.com/wiki/56/

回答by Onkar Janwa

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!'),    

回答by Rohit Suthar

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!');
    }

回答by Howard Panton

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

对于 Yii2,我在名为 Register 的模型中使用了以下内容,该模型将使用用户类。

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

您需要使用 targetClass 并为 Class User 放置 Namepsace

回答by Rizwan Shamsher Kaim Khani

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.

在这里,我想对电子邮件进行验证,这是唯一的,我的模型类名称是 User,attributeName 是表的字段名称,即电子邮件,如果电子邮件已经存在于您的表中,则显示消息。

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

如果出现错误,则您可以更改表格并使电子邮件字段唯一。

ALTER TABLE user ADD UNIQUE (email)

ALTER TABLE 用户添加唯一(电子邮件)

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

就是这样。谢谢

回答by Bhatt Akshay

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.

转到模型 -> 打开 -> Users.php -> 如下所述修改行。

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

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

现在转到 views-> users -> Open _form.php-> 编写如下代码

<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

现在转到 Controller->open UsersController.php -> 编写如下代码

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

谢谢