How Can I Validate Either One Of The Textfields To Be Filled In Yii

I’m new to Yii framework. Now in my form I have two fields FirstName and LastName.

I want to validate such that either of the two is filled. i.e not both should be empty.

Suppose the user leaves both the fields empty it should not allow submit. The user should atleast enter any of these fields.

Rules

public function rules()


        {


                return array(





                        array('Firstname,Lastname, email, subject, body', 'required'),


                        array('email', 'email'),


                        array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),


                );


        }

How can I do this?

I think you have two solution:

  1. Create a custom validate;

  2. Subclass beforeValidate() method of your model and insert rules to check;

In both solution you need to remove that two fields from ‘require’ validator.

Can you please explain in detail. I’m new to Yii framework. I did not get you

First solution.

Read this:

http://www.yiiframework.com/wiki/168/create-your-own-validation-rule/

http://www.yiiframework.com/wiki/56/

Second solution.

In your model insert this method:




public function beforeValidate()

{

     if (parent::beforeValidate())

     {

     	if (($this->name==null)&&($this->surname==null))      

	{

		$this->addError('name', 'name or surname should be filled');

		return false;

	}


        return true;

     }

     return false;

}



Remember to remove name and surname fields from ‘require’ validator in rules.