mh469
(Martinauschemnitz)
June 10, 2011, 8:55pm
1
Hi!
I do want to add the following rule to my model:
if checkbox1 is checked, field2 and field3 are required
if checkbox4 is checked, field5 is required to be an e-mail address
How can I specify this? Problem seems to be that rules() is called too early, not just before validation, so I cannot dynamically concatenate the rules array.
softark
(Softark)
June 11, 2011, 1:36am
2
I would write a validation method for field2 and field3 in the model class.
public function rules()
{
return array(
....
array('field2, field3', 'validateF2andF3'),
....
);
}
public function validateF2andF3($attribute, $params)
{
if ( $this->checkbox1 > 0 )
{
if ( $this->$attribute == '' )
{
$this->addError($attribute, 'Error message.');
}
}
}
mh469
(Martinauschemnitz)
June 11, 2011, 6:38am
3
Thanks. But can I use the build-in validators this way? (e.g. for the e-mail address)
softark
(Softark)
June 11, 2011, 8:46am
4
Um, I haven’t done it myself yet, but looking it up in the reference of CEmailValidator, I think something like this should work.
public function rules()
{
return array(
....
array('field5', 'validateF5'),
....
);
}
public function validateF5($attribute, $params)
{
if ( $this->checkbox4 > 0 )
{
$ev = new CEmailValidator();
$ev->allowEmpty = false;
$ev->validate($this, $attribute);
}
}
Please give it a try, and let me know if I’m wrong.
mh469
(Martinauschemnitz)
June 11, 2011, 2:13pm
5
Thanks a lot! My solution is
public function validateF5($attribute, $params)
{
if ($this->checkbox4) {
$ev = new CEmailValidator();
$ev->attributes = explode(',', $attribute);
foreach ($params as $key=>$value)
$ev->$key = $value;
$ev->validate($this);
}
}
mh469
(Martinauschemnitz)
June 11, 2011, 5:22pm
6
Even better:
public function validateF5($attribute, $params)
{
if ($this->checkbox4) {
$ev = CValidator::createValidator('required', $this, $attribute, $params);
$ev->validate($this);
}
}
sidtj
(sdlins)
January 19, 2012, 12:46am
7
Now there is an extension to do it:
Yii Conditional Validator
Posting for the case someone arrives here coming from a search page.
drmovi
(Drmovi)
October 5, 2012, 11:59pm
8
thanks for this good article