接受两种格式的电子邮件,即abc.def ANDabc.def@testdomain.com.


Email to be accepted in 2 formats i.e. abc.def AND abc.def@testdomain.com

我需要将电子邮件验证为电子邮件(abc.def@testdomain.com)同时作为用户名(abc.def)。我使用了Yii电子邮件验证,这是一种严格的验证,但我不必更改它,因为它在项目中的许多其他地方都在使用。

但是,我需要为单个模型添加自定义用户名验证和YII电子邮件验证。

以下是实现这一点的准则。

public function rules() {
    $rules = array(
        array('email', 'required', 'message'=>'Please complete {attribute}'),
        array('email', 'EmailCustom'),
        array('email', 'unique')
    );
}

而EmailCustom验证器类是:

class EmailCustom extends CEmailValidator
{
    public $pattern = '/^[ ]*[a-zA-Z0-9!#$%&''*+''/=?^_`’{|}~-]+(?:'.[a-zA-Z0-9!#$%&''*+''/=?^_`’{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?'.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?[ ]*$/';
    protected function validateAttribute($object, $attribute)
    {
        $pattern = '/^[ ]*[a-zA-Z0-9!#$%&''*+''/=?^_`’{|}~-]+(?:'.[a-zA-Z0-9!#$%&''*+''/=?^_`’{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?'.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?[ ]*$/';
        if ($object->visitor_card_status == 2) {
            if (!preg_match($pattern, $object->$attribute)) {
                if ($object->$attribute !== $object->first_name . '.' . $object->last_name) {
                    $this->addError($object, $attribute, 'Email is incorrect format');
                }
            }
        } else {
            if (!preg_match($pattern, $object->$attribute)) {
                $this->addError($object, $attribute, 'Email is incorrect format');
            }
        }
    }
    public function clientValidateAttribute($object, $attribute)
    {
        if ($this->validateIDN)
        {
            Yii::app()->getClientScript()->registerCoreScript('punycode');
            // punycode.js works only with the domains - so we have to extract it before punycoding
            $validateIDN='
                            var info = value.match(/^(.[^@]+)@(.+)$/);
                            if (info)
                                value = info[1] + "@" + punycode.toASCII(info[2]);
                            ';
        } else {
            $validateIDN = '';
        }
        $message = $this->message!==null ? $this->message : Yii::t('yii','{attribute} is not in a recognised format. <span style="text-transform:capitalize;">Please </span>revise.');
        $message = strtr($message, array(
            '{attribute}'=>$object->getAttributeLabel($attribute),
        ));
}

因此,在Validator Class的模式中应该添加什么才能只接受两个FORMATS:abc.defabc.def@testdomain.com

希望很快收到你的来信。感谢

实际上,我已经更新了接受这两种格式的模式,并且使用Yii Validator函数可以完成任务。

下面是接受这两种格式的模式。即abc.def和string@testdomain.com

/(^[ ]*[a-zA-Z0-9!#$%&''*+''/=?^_`’{|}~-]+(?:'.[a-zA-Z0-9!#$%&''*+''/=?^_`’{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?'.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?[ ]*$)|([a-zA-Z0-9]+'.[a-zA-Z0-9]+)/

我希望它能帮助其他人。感谢