具有特殊条件的 yii1 验证规则
yii1 validation rule with special conditions
我在使用 Yii1 验证时遇到问题。我有联系人类型的列表框,我希望电子邮件验证仅在选择通过电子邮件联系时才有效。所以我使用自定义规则来检查它是否不为空:
public function customEmailValidation($attribute, $params)
{
if(!$this->hasErrors())
{
if($this->contact_type == 2)
{
if($this->attribute == "") $this->addError($attribute, "Enter email address");
}
}
}
但之后我想使用第二条规则来检查电子邮件格式是否正确,我该如何实现?在主要规则中,我可以通过以下方式检查它:
['email', 'email', 'message' => 'wrong email format'],
但是只有当 $this->contact_type == 2 时我才能检查它?我还需要编写自定义规则,还需要编写正则表达式来检查电子邮件格式吗?或者我可以在自定义验证中使用主要验证规则?
谢谢。
首先从 rules()
.
中删除 email
验证器
使用相同的代码,在您的自定义验证中,您可以 'attach' any existing Yii validator or create your own / custom validator. In your case, Yii email validator 就足够了,我们会将其附加到您的自定义验证中:
public function customEmailValidation($attribute, $params)
{
if(!$this->hasErrors())
{
if($this->contact_type == 2)
{
if($this->attribute == "")
{
$this->addError($attribute, "Enter email address");
}
if( strlen($this->attribute) > 0 )
{
$emailValidator = new CEmailValidator;
if ( ! $emailValidator->validateValue($this->attribute) )
{
$this->addError($attribute, 'Wrong email');
}
}
}
}
}
我在使用 Yii1 验证时遇到问题。我有联系人类型的列表框,我希望电子邮件验证仅在选择通过电子邮件联系时才有效。所以我使用自定义规则来检查它是否不为空:
public function customEmailValidation($attribute, $params)
{
if(!$this->hasErrors())
{
if($this->contact_type == 2)
{
if($this->attribute == "") $this->addError($attribute, "Enter email address");
}
}
}
但之后我想使用第二条规则来检查电子邮件格式是否正确,我该如何实现?在主要规则中,我可以通过以下方式检查它:
['email', 'email', 'message' => 'wrong email format'],
但是只有当 $this->contact_type == 2 时我才能检查它?我还需要编写自定义规则,还需要编写正则表达式来检查电子邮件格式吗?或者我可以在自定义验证中使用主要验证规则?
谢谢。
首先从 rules()
.
email
验证器
使用相同的代码,在您的自定义验证中,您可以 'attach' any existing Yii validator or create your own / custom validator. In your case, Yii email validator 就足够了,我们会将其附加到您的自定义验证中:
public function customEmailValidation($attribute, $params)
{
if(!$this->hasErrors())
{
if($this->contact_type == 2)
{
if($this->attribute == "")
{
$this->addError($attribute, "Enter email address");
}
if( strlen($this->attribute) > 0 )
{
$emailValidator = new CEmailValidator;
if ( ! $emailValidator->validateValue($this->attribute) )
{
$this->addError($attribute, 'Wrong email');
}
}
}
}
}