Validation without a model in CakePHP

CakePHP offers an awesome set of validation methods, but they rely on defining what you want to validate within a model. Sometimes you just want to quickly validate a certain piece of data, or validate a set of data iteratively without touching the model. For that, you can import the Validation class and use its methods directly in the controller.

For example – I had a comma separated list of phone numbers and wanted to strip out any invalid ones.

App::import('Core', 'Validation');
$valid_recipients = array();
foreach($recipients as $rcpt) {
      $rcpt = trim($rcpt);
      if(Validation::phone($rcpt)) {
            $valid_recipients[] = $rcpt;
      }
}

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*