Validating and Sanitizing data in CakePHP 3

CakePHP 3 book – Validators

CakePHP 3 book – Table Objects

CakePHP 3 book – Saving data

Countries Table SQL schema:

CREATE TABLE IF NOT EXISTS `countries` (
  `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'Uknown', 
  `code` VARCHAR(2) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'UN', 
  `modified` DATETIME NULL,
  `created` DATETIME NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`),
  UNIQUE KEY `code` (`code`),
  KEY `created` (`created`),
  KEY `modified`	(`modified`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

In your Table Model for ex. CountriesTable append necessary use references:

use CakeValidationValidator;
use CakeORMRulesChecker;
use CakeORMRuleIsUnique;
use CakeEventEvent, ArrayObject;

Add validationDefault function to CountriesTable class:

public function validationDefault(Validator $validator)
{
    $validator->provider('custom', 'AppModelValidationMyValidation');
 
    $validator 
        ->requirePresence('name', 'create')
        ->notEmpty('name')
        ->add('name', 'minlength',  ['rule'  =>  ['minLength', 1]])
        ->add('name', 'maxlength',  ['rule'  =>  ['maxLength', 50]])
        ->add('name', 'regex',      ['rule'  =>  'countryname', 
            'provider' =>  'custom'])
 
        ->requirePresence('code', 'create')
        ->notEmpty('code')
        ->add('code', 'minlength',  ['rule'  =>  ['minLength', 2]])
        ->add('code', 'maxlength',  ['rule'  =>  ['maxLength', 2]])
        ->add('code', 'regex',      ['rule'  =>  'countrycode', 
            'provider' =>  'custom'])
	;
 
	return $validator;
}

Create class src/Model/Validation/MyValidation:

namespace AppModelValidation;
use CakeValidationValidation;
 
class MyValidation extends Validation
{
 
    public static function countryname($check)
    {
        if (is_array($check)) {
            extract(static::_defaults($check));
        }
 
        if (empty($check) && $check != '0') {
            return false;
        }
 
        return self::_check($check, '/^[a-zA-Z();' ]+$/');
    }
 
    public static function countrycode($check)
    {
        if (is_array($check)) {
            extract(static::_defaults($check));
        }
 
        if (empty($check) && $check != '0') {
            return false;
        }
 
        return self::_check($check, '/^[A-Z]+$/');
    }
 
}

Add function buildRules for the last validation rules:

public function buildRules(RulesChecker $rules)
{
    $rules->add($rules->isUnique(['name']));
    $rules->add($rules->isUnique(['code']));
 
    return $rules;
}

Sanitize data before validation:

public function beforeMarshal(Event $event, ArrayObject $data, ArrayObject $options)
{
	$data['code'] = substr(preg_replace('/[^A-Z]/', '', strtoupper($data['code'])), 0, 2);
	$data['name'] = ucwords(substr(preg_replace('/[^a-zA-Z();' ]/', '', $data['name']), 0, 50));
}
Categories: CakePHP, PHP Tags: , , ,
%d bloggers like this: