Yii 限制电子邮件域-VAII

Yii 限制电子邮件域-VAII,yii,Yii,我在注册表单中有电子邮件字段 我想用数据库验证电子邮件域,例如 Email adress is : example@work.com or etc@etc.com 现在我要验证work.com或etc.com是否在db中列出,如果不是,则不应为vaidate 有人能帮我吗?您可以通过在模型的规则部分添加自定义yii验证器来实现这一点。下面是一些示例代码: public $email; // This is the field where the email is stored /** *

我在
注册
表单中有
电子邮件
字段

我想用数据库验证电子邮件域,例如

Email adress is : example@work.com  or etc@etc.com
现在我要验证
work.com
etc.com
是否在db中列出,如果不是,则不应为vaidate


有人能帮我吗?

您可以通过在模型的规则部分添加自定义yii验证器来实现这一点。下面是一些示例代码:

public $email; // This is the field where the email is stored

/**
 * @return array validation rules for model attributes.
 */
public function rules()
{
    return array(
       array('email', 'checkDomain'),
    );
}
之后,您可以添加自定义验证函数

public function checkDomain($attribute,$params)
{
    $sEmailDomain = substr(strrchr($this->email, "@"), 1);

    // Check if the domain exists
    ...
    // If the domain exists, add the error
    $this->addError('email', 'Domain already exists in the database');
}

更多信息可以在这里找到:

您可以通过在模型的规则部分添加自定义的yii验证器来实现这一点。下面是一些示例代码:

public $email; // This is the field where the email is stored

/**
 * @return array validation rules for model attributes.
 */
public function rules()
{
    return array(
       array('email', 'checkDomain'),
    );
}
之后,您可以添加自定义验证函数

public function checkDomain($attribute,$params)
{
    $sEmailDomain = substr(strrchr($this->email, "@"), 1);

    // Check if the domain exists
    ...
    // If the domain exists, add the error
    $this->addError('email', 'Domain already exists in the database');
}
更多信息可在此处找到:

代码:

public function validate($attributes = null, $clearErrors = true) {
    parent::validate($attributes, $clearErrors);
    if (!$this->hasErrors('email')) {
        $a = explode('@', $this->email);
        if (isset($a[1])) {
            $record = AllowedDomains::model()->findByAttributes(array('domain'=>$a[1]));
            if ($record === null) {
                $this->addError('email', "This domain isn't allowed");
            }
        }
    }
    return !$this->hasErrors();
}
注:

  • 将此代码放入模型中
  • 电子邮件-包含电子邮件地址的字段
  • AllowedDomains—包含允许的域的表的CActiveRecord
  • 域-替换为正确的数据库字段
  • 不要忘记在rules()函数中添加电子邮件验证程序。这将过滤掉无效的电子邮件地址,如果出现问题,上述代码将不会运行
代码:

注:

  • 将此代码放入模型中
  • 电子邮件-包含电子邮件地址的字段
  • AllowedDomains—包含允许的域的表的CActiveRecord
  • 域-替换为正确的数据库字段
  • 不要忘记在rules()函数中添加电子邮件验证程序。这将过滤掉无效的电子邮件地址,如果出现问题,上述代码将不会运行

可以这样做,但是如果您有数百个需要验证的属性,那么验证功能将变成一个大烂摊子:-)谢谢。。。具有数百个属性的好例子…:主要的想法是,如果电子邮件地址已经存在,则避免运行验证程序errors@icefront,它向我显示了此错误致命错误:已达到最大函数嵌套级别“100”,正在中止!在第219行的D:\wamp\www\yii\framework\base\CComponent.php中,我删除了递归函数调用,它成功了!父::验证($attributes,$clearErrors);可以这样做,但是如果您有数百个需要验证的属性,那么验证函数将变成一个大烂摊子:-)谢谢。。。具有数百个属性的好例子…:主要的想法是,如果电子邮件地址已经存在,则避免运行验证程序errors@icefront,它向我显示了此错误致命错误:已达到最大函数嵌套级别“100”,正在中止!在第219行的D:\wamp\www\yii\framework\base\CComponent.php中,我删除了递归函数调用,它成功了!父::验证($attributes,$clearErrors);