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

后端 未结 6 983
日久生厌
日久生厌 2020-12-18 21:15

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条回答
  •  有刺的猬
    2020-12-18 21:42

    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

提交回复
热议问题