【发布时间】:2016-02-21 03:59:55
【问题描述】:
我需要将电子邮件验证为 EMAIL(abc.def@testdomain.com),同时验证为 USERNAME (abc.def)。我使用了 Yii EMAIL Validation,它是严格的验证,但我不必更改它,因为它在项目的许多其他地方都在使用。
但是,我需要为单个模型添加自定义用户名验证和 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的模式中应该添加什么来只接受两种格式:abc.def和abc.def@testdomain.com
希望很快收到您的来信。谢谢
【问题讨论】:
标签: php validation email yii