PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, February 28, 2022

[FIXED] yii1 validation rule with special conditions

 February 28, 2022     php, validation, yii, yii1.x     No comments   

Issue

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.


Solution

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


Answered By - Alejandro Quiroz
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing