Validating a checkbox in CakePHP 1.2

In a few simple words: use the ‘comparison’ rule to validate a checkbox.

To give you an example, let’s say a user needs to agree to the terms of service when registering a new account. In your User model you setup a rule for the checkbox as follows:

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

As you can probably guess from the code the empty checkbox will send a default value of zero, and that is what your validation rule is going catch. The ‘on’ key will ensure that the rule is only enforced on account creation and not when the User is editing an existing account.

%d bloggers like this: