Validation on optional fields

CakePHP’s allowEmpty option makes performing validation on optional fields remarkably simple, even ones with multiple validation rules.

Let’s assume we want to collect a user’s zip code. We configure an entry in our model’s $validate array, taking advantage of CakePHP’s built-in numeric validation:

public $validate = array(
   'zip' => array(
      'rule' => 'numeric',
      'message' => 'Numbers only, please.'
   )
);

In submitting the form, users are obligated to provide their zip code, and it had better be numbers only, otherwise they’ll receive a rather snippy error message in response.

Now let’s say we have a change of heart and we decide not to require them to provide their zip code. That said, we still do have standards so if they volunteer the information, it had better be all numbers, damnit. Enter allowEmpty:

public $validate = array(
   'zip' => array(
      'rule' => 'numeric',
      'message' => 'Numbers only, please.',
      'allowEmpty' => true
   )
);

The red asterisk is gone from the zip code field and our user thinks we’re just that little bit cooler and more relaxed. However, if they try to “garbage in” us, we’re ready for them.

For fields with multiple validation rules, the allowEmpty goes in the first rule. If, for example, our zip codes have to be numeric and at least 5 digits long — but still optional — we’d write it this way:

public $validate = array(
   'zip' => array(
      'numeric' => array(
         'rule' => 'numeric',
         'message' => 'Numbers only, please.',
         'allowEmpty' => true
      ),
      'length' => array(
         'rule' => array('minLength', 5),
         'message' => 'Zip codes need to be at least 5 digits long.'
      )
   )
);