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:

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:

'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.

Published by Abou Kone

I am a front end architect with 10+ years of experience in web development. The best part of the process for me is converting ideas into code and solving the technical problems that come along. Alongside providing technical leadership and architectural support to projects spanning multiple industries, I am also experienced in leading discussions with designers, developers, and business stakeholders helping to guide teams in turning complex business workflows or data into easy-to-use web and mobile interfaces. I believe in delivering high quality products and am constantly looking into improving the process and tools use to achieve this goal.

2 thoughts on “Validating a checkbox in CakePHP 1.2

Leave a Reply

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

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

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s

%d bloggers like this: