Dependent required validator

Is there a good Yii way to solve this situation?

DDD and Fone Number.

In BD both are concated, but in html they are splited in 2 fields.

My problem is… I would like only to set "required = true" IF DDD is not NULL. Else, both are not required.

Enlight me please!

Sorry just a little confused on the language used. What is DDD and I’m assuming you meant phone number.

I get that the two are together as one string so whatever format DDD is and then DDDXXXXXXXXXX (where you have area code and then 7 digit phone number).

If you can clarify a little I’d be glad to give you some advice on rule sets.

I live in Brazil. And DDD mean the state code. It’s a 2 or 3 digit integer numeric.

I can type in a simple text field: (47) 3344-8877

Or, I can type in two form (like my case):

DDD in a text field: 47

Number: 3344-8877

Take a look in the attachment.

The second field is "required true" only if DDD is not empty

So you want the user to either fill in the DDD or the number or both?

I’m not too sure. It is a good question. Would using the same value for both text inputs work?

Conditional rules are not available so far, but you may want to extend beforeValidate() of your model, and add an error and deny the saving process by returning false.

I did not see any attachment however Pestaa’s right, there is no conditional setup with rules and validations right now.

On a side note you can also develop your own rule by extending the CValidator class in a component.

Here’s information on extending a validator:

Once you extend it, just make a new function that takes the two parameter values, DDD and phone #.

Then inside that function just do your logic:

if(DDD != NULL)


     // make sure phone # is also not Null

     // Do any other rules and checks you want to do

     return true; // for a pass

     return false; // for a fail - this will effectively stop the save process until the input is corrected by the user.


Then in your model just assign the rule:

array('DDD', 'phone#', 'myCustomRuleFunction');

Not sure if you’d join the DDD and phone# as one but that would imply you’re doing the same function to both which would not be accurate.

Now an alternative, since you have it stored in the DB as one string, you can just pass the DDD and if it’s inputted (not null) then you can still access the phone# attribute (from your form) because you’re still in the model and thus it’s all shared). This means you can evaluate and combine them both as 1 to save to the db.

Hope that helps.

I would take pestaa suggestion but whoopass give us a good ideia.

Thank you all.