Many-Many Validation

Hi all, I need to validate a Many-Many relation:

I have three tables, Post, Categories and pivot table post_categ. The structure of these tables is obvious. Let me know if you need me to post their structure as well.

What I want to validate is that when user Insert Post, it checks if any category is selected? If not not, it should return a validation error.

Also, is there any way to trigger some validation error manually???


You can trigger validation errors ( You can have your validation check for whatever requirements you want.

Thanks for your reply…

Since the field I am trying to validate does not included in the Page model, I did the following:

Categories are displayed as checkboxes and will be submitted in form of an array.

if( count($Categories) == 0 )

$PageModel->addError('Ctg','Please select category');

Although it is working but please let me know if this right way to do it?

One more thing to ask:

array('attribute', 'required')

Is it necessary for the attribute to be part of model or it can be any text field in the form that receive user input?


Let me re-describe my question:

How do I put validation rules for those form inputs, which are not included in model but receives input from user?

For example, suppose my model attributes are: Model-Post => (title, content, date) and my Post form is:

Title: ________________

Content: ______________

Date: _________________

Status: _______________

Now, how do I validate Status field as this is not included in Model attributes???


I believe you can do two things.

  1. Add another field in the model, Lets say public $status in your model class and define a rule for it.

  2. Manually validate that field in your controller for each time.

I personally prefer the first way but it can be worked out depending upon your needs.