I need emails to be validated as a EMAIL(abc.def@testdomain.com) and at the same time as a USERNAME (abc.def). I have used Yii EMAIL Validation which is strict validation but i have not to change it because it is using in many other places in the project.
However, i need to add CUSTOM USERNAME VALIDATION along with YII EMAIL VALIDATION for a single MODEL.
Below is the Code to do that.
public function rules() {
$rules = array(
array('email', 'required', 'message'=>'Please complete {attribute}'),
array('email', 'EmailCustom'),
array('email', 'unique')
);
}
Whereas EmailCustom Validator Class is:
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),
));
}
So, What should be added in the pattern of Validator Class to accept only two FORMATS: abc.def and abc.def@testdomain.com
Hope to hear from you soon. Thanks