Validating a checkbox in CakePHP 1.2

I was looking for a good way to validate a checkbox for a site i was working on, and came upon this link that pointed me in the right direction:

http://teknoid.wordpress.com/2008/06/10/validating-a-checkbox-in-cakephp-12/

I followed the instruction, mainly:


'agree' => array(
'rule' => array('comparison', '!=', 0),
'required' => true,
'message' => 'You must agree to the terms of use',
'on' => 'create'
)

But for some reason, it would not work for me no matter what i tried, my checkbox still failed validation, even when the box was checked. I narrowed down the problem to the:

'required' => true,

line. It seemed to break the validation for a reason I do not know. So removing this line should get you through the validation correctly. I did my validation another way by using a new CakePHP core validation function, inList. Here is the code i use to account for all possible values i am expecting my checkbox to have when checked. I added it to the necessary model class:



'terms_of_use'=>array(
'rule' => array('inList', array('1',1,'true', true,'on')),
'message' => 'You need to accept the Terms Of Use to be able to register.')

As you can see, the ‘inList’ validation will check to see if the checkbox value is within the array values submitted so you can account for all possible values you need your checkboxes to have to pass validation. This will improve reusability within your code.

Hope It Helps.

Advertisement

2 responses to “Validating a checkbox in CakePHP 1.2”

  1. Thanks man! Your solution was the best i’ve found!

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: