我有email
形式的signup
字段,
我想用数据库验证电子邮件域,例如
Email adress is : example@work.com or etc@etc.com
现在我要验证db中是否列出了work.com
或etc.com
,如果没有,那么它不应该是vaidate。!
任何人都可以帮我这个吗?
答案 0 :(得分:2)
代码:
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();
}
注意:
答案 1 :(得分:1)
您可以通过在模型的规则部分添加自定义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');
}
可在此处找到更多信息:http://www.yiiframework.com/wiki/168/create-your-own-validation-rule/