vyckiuz
vyckiuz

Reputation: 157

yii1 validation rule with special conditions

Im having trouble with Yii1 validation. I have listbox with contact types and i want email validation to work only when contact via email is choosed. So Im using custom rule to check if its not empty:

public function customEmailValidation($attribute, $params)
{
    if(!$this->hasErrors())
    {
        if($this->contact_type == 2)
        {
            if($this->attribute == "") $this->addError($attribute, "Enter email address");
        }
    }
}

But after that I want to use second rule to check if email format is good, how i can achieve it? In main rules i can check it by this:

['email', 'email', 'message' => 'wrong email format'],

but how i can check it only when $this->contact_type == 2 ? I need to write custom rule also and I need to write regex to check email format? Or somehow i can use main validation rules in custom validations?

Thank you.

Upvotes: 0

Views: 1835

Answers (1)

Alejandro Quiroz
Alejandro Quiroz

Reputation: 2684

First remove email validator from rules().

Using your same code, in your custom validation, you can 'attach' any existing Yii validator or create your own / custom validator. In your case, Yii email validator is enough and we will attach it to your custom validation:

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');
               }
            }
        }
    }
}

Upvotes: 1

Related Questions