Validation framework

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

It is important to notice that it is the responsibility of the developer 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.

Quick exemple


class ValidationEntity extends PorteRecord{
  public $meta_fields = 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'), // 1978 09 10 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'=>true,'not_null'=>true),
  );
}

$validation = new ValidationEntity();
print_r($validation->validate());

/** will print:
Array
(
  [string] => not_null
  [integer] => not_null
  [date] => not_null
  [validation_belongs_to_entity] => not_null
)
*/

$validation->setString('a');
$validation->setInteger('ab');
$validation->setEmail('invalid email');
$validation->setDate('274200000');
$validation->setGenderStringString('N');
$validation->setGenderIntArray(3);
print_r($validation->validate());

/** will print:
Array
(
  [string] => min
  [email] => email
  [integer] => min
  [date] => min
  [gender_string_string] => one_of
  [gender_int_array] => one_of
  [validation_belongs_to_entity] => not_null
)
*/
    

Records configuration

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

Open Source Object Relational Mapping in PHP

Download Porte 0.2.1