ModelValidation
Filepath: phork/php/ext/helpers/ModelValidation.class.php
The ModelValidation class is an extension of the CoreModelHelper class that's used to validate a record object before saving it to the database.
The validation helper has a validateAll event method called before saving the object which can return a $blnSkipSave flag if the record doesn't validate. This will prevent the record from being saved.
In additional to the standard config-based validation it's possible to defined a custom function to validate either the entire record or a single property.
Generally this helper should be appended in the model's constructor along with the validation definitions.
Example (from a model constructor)
if (AppLoader::includeExtension('helpers/', 'ModelValidation')) {
$this->appendHelper('validation', 'ModelValidation', array(
'Id' => array(
'Property' => 'userid',
'Unique' => true,
'Type' => 'integer',
'Error' => 'Invalid ID'
),
'Username' => array(
'Property' => 'username',
'Unique' => true,
'Required' => true,
'Type' => 'string',
'RegEx' => '/^[0-9a-z]{3,20}$/i',
'Error' => 'Invalid username. It must be between 3 and 20 characters in length, containing only a-z and 0-9.',
),
'Password' => array(
'Property' => 'password',
'Required' => true,
'Type' => 'string',
'Error' => 'Invalid password'
),
'Email' => array(
'Property' => 'email',
'Unique' => true,
'Required' => true,
'Type' => 'email',
'CheckMx' => false,
'Error' => 'Invalid email address'
),
'Birthdate' => array(
'Property' => 'birthdate',
'Required' => true,
'Type' => 'string',
'RegEx' => '/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/',
'Error' => 'Invalid birthdate'
),
'CustomProperty' => array(
'Property' => 'property',
'Function' => 'validateProperty',
'Error' => 'Missing property'
),
'CustomGeneral' => array(
'Function' => 'validateGeneral'
)
));
//initialize the validation helper
$this->initHelper('validation', array('validateAll'));
}
Example Custom Validators (from a model)
public function validateProperty($strProperty) {
return $this->current()->get($strProperty) === $this->current()->get($strProperty . '_confirm');
}
public function validateGeneral() {
$blnResult = true;
if (!$this->current()->get('foo')) {
trigger_error(AppLanguage::translate('Missing value for foo'));
$blnResult = false;
}
if (!$this->current()->get('bar')) {
trigger_error(AppLanguage::translate('Missing value for bar'));
$blnResult = false;
}
return $blnResult;
}