conditional form rule

Hello.

How can I enable/disable form rule using some condition?

Example:




public function rules()

	{

		return array(

			array('email', 'email', 'enable' => app()->param['checkEmail'])

		);

	}



So rule is validated if app->param[‘cehckEmail’] is true.

Thank you.

Try this




public function rules()

{

  return array(

    array(app()->param['checkEmail']?'email':'', 'email')

  );

}



Edit:

I accidentally modified the attribute instead of the rule specifier. This is what I first intended to do:




public function noRule($attribute,$params) { }


public function rules()

{

  return array(

    array('email', app()->param['checkEmail']?'email':'noRule')

  );

}



/Tommy

I want to validate the field if and only if the field is not empty, how should I do it?

For example, I don’t want to put require restriction on the email field, but if it is entered it should be checked for valid email address.

Thanks!

If I understand your question correctly, use the ‘email’ validator but omit the ‘required’ validator.

/Tommy

There is magic attribute called allowEmpty :)

Thank you all of you for your replies!

 And if I want to validate the fields which are dependent on values of other fields, how should I do it?

For example, I have a check box for advanced inputs. If user checks it, I need to apply the validation.

Thanks again!

tri, thanks!

Your solution is what I was looking for.

you can always declare custom function in your rules such as:


public function rules()

	{

     return array(

            array('input_field','check'),

  }

}


protected function check()

{

 validate as you wish here and if your application hits into an error just do:

  $this->addError('input_field','error message');

}

hope this helps