Custom Validation (Or Not) Two Fields, One Of Any Required

Hey everyone

I have this model that has two fields and any of those is required, how do I validate this?

I have tried using a custom validation rule, like this one:

public function validateFields1and2($attribute, $params)


	if (trim($this->field1) == '' && trim($this->field2) == '') {

		$this->addError('field1', 'Please fill Field1 and/or Field2');



Almost works, but the problem is that if I empty both fields, I get the error on the first one, that’s cool. If I fill the second field, the error on the first field remains and it should go away. Not cool.

So, what I need to do is:

1- If both fields are empty: error (it could be shown in one or both fields, it doesn’t matter as long as it can be removed, see 2)

2- If any of the two fields is valid, then remove errors on both fields <-- this one’s giving me a headache.

Any ideas?


What you’ve shown should work. You’re only adding the error if both of the fields are blank, so you don’t need to remove anything.

The rule works, the problem is that if at first, the fields don’t pass validation (both fields empty) the error is set: this is fine.

If I fill field2, then validation passes but the error message stays there and this gives the user the wrong impression that it is still invalid, see what I mean?

I have attached images of the fields and the validation process.

The first one shows "apellido paterno" and "apellido materno" empty and the error message.

The second image shows that I have filled "apellido paterno". The error message for "apellido paterno" dissapears, but not on "apellido materno" (and it should, its valid).

The third one is the same thing, but inverse, if I leave "apellido paterno" empty and fill "apellido materno", the error goes away on "apellido materno" but not on "apellido paterno".

Only if both are filled, the errors go away.

Is there a way to "remove" the error? or maybe "make" valid a field from Yii?