looking for validation rule which checks entry in EITHER this OR that field

Hello,

I’m looking for your help, as I don’t know how to handle the following situation with validation rules. Could anybody help me please?

I have a database table "maintable" which is related to either "table_a" OR "table_b".

MAINTABLE

id

table_a_id (INT)

table_b_id (INT)

If table_a_id is specified (>0) table_b_id will be "0".

If table_b_id is specified (>0) table_a_id will be "0".

An entry in one of both fields is mandatory. (Both fields together may not be "0".)

Is there a way to get this situation indicated in the validation rules? Something that produces a validation error like "You need to specify either table_a_id or table_b_id!"…

Thank for your help in advance!

You need to create a custom validator. It can be a method-based one or a class.

A very simple method-based validator looks like:




public function rules()

{

    return array(

        array('table_a_id', 'validateId'),

    );

}


public function validateId($attribute, $params)

{

    if ($this->table_a_id == 0 && $this->table_b_id == 0)

        $this->addError('table_a_id', 'Id can not be empty');

}



Examples of class based validators are all you usually use: CStringValidator, CRequiredValidator etc.

For more precise check you’ll probably want to extend CExistValidator.

Thank you Andy for the quick reply,

I will check that out!