0
我需要將電子郵件驗證爲EMAIL([email protected]),同時還需要USERNAME(abc .DEF)。我已經使用Yii EMAIL驗證,這是嚴格的驗證,但我沒有改變它,因爲它在項目的許多其他地方使用。電子郵件被接受爲兩種格式,即abc.def和[email protected]
但是,我需要爲單個模型添加CUSTOM USERNAME VALIDATION和YII EMAIL VALIDATION。
下面是要做到這一點的代碼。
public function rules() {
$rules = array(
array('email', 'required', 'message'=>'Please complete {attribute}'),
array('email', 'EmailCustom'),
array('email', 'unique')
);
}
而EmailCustom Validator類是:
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),
));
}
那麼,究竟應該在驗證程序類的模式被添加到只接受兩種格式:abc.def和[email protected] .com
希望能儘快聽到您的消息。謝謝