Validation: Integrated validation framework

Porte comes with a simple validation framework. It is possible to implements complex validation rules by overwriting the "validate" method.

Important: it is the program responsibility to call the validate method as no internal method will do it automatically (the "save" method included).

Expected behavior of the "validate" method

The method returns "null" if the record is valid or an array for which each key corrosponds to the invalid field and each value corresponds to the type of error.

At a first sight, this might not look logical but it makes its usage esthetic when integrated in a if condition

if($validation = $user->validate()){
	print_r($validation);
}else{
	$user->save();
}

Quick exemple

class User extends PorteRecord{
	public $config = array(
		'properties'=> array(
			'id'=>array('length'=>11,'not_null'=>true),
			'string'=>array('length'=>20,'not_null'=>true,'min'=>2),
			'email'=>array('length'=>20,'email'=>true),
			'integer'=>array('type'=>'int','length'=>20,'not_null'=>true,'min'=>2),
			'date'=>array('type'=>'date','not_null'=>true,'length'=>20,'min'=>'274230000'), // sept 10th 1978 00:00
			'gender_string_string'=>array('type'=>'string','one_of'=>'M,F'),
			'gender_string_array'=>array('type'=>'string','one_of'=>array('M','F')),
			'gender_int_string'=>array('type'=>'int','one_of'=>'1,2'),
			'gender_int_array'=>array('type'=>'int','one_of'=>array(1,2)),
			'validation_belongs_to_entity'=>array('belongs_to'=>array('type'=>'user'),'not_null'=>true)
		)
	);
}

$user = new User();
$validation = $user->validate();
assert( 'not_null' === $validation['string']);
assert( 'not_null' === $validation['integer']);
assert( 'not_null' === $validation['date']);
assert( 'not_null' === $validation['validation_belongs_to_entity']);

$user->setString('a');
$user->setInteger('ab');
$user->setEmail('invalid email');
$user->setDate('200000000');
$user->setGenderStringString('N');
$user->setGenderIntArray(3);
$validation = $user->validate();
assert( 'min' === $validation['string']);
assert( 'email' === $validation['email']);
assert( 'min' === $validation['integer']);
assert( 'min' === $validation['date']);
assert( 'one_of' === $validation['gender_string_string']);
assert( 'one_of' === $validation['gender_int_array']);

Records configuration

Validation rules are declared for each record property throught the "meta_fields" array by adding one of the following relevant keywords: