-
Notifications
You must be signed in to change notification settings - Fork 2
Home
Craig Manley edited this page Feb 17, 2016
·
11 revisions
PHP validation library. This is similar to Perl's Params::Validate. You can use it to validate anything, but most commonly it is used for validating input from HTML forms, fields while reading CSV files, function parameters, ORM arrays, etc.
- PHP 5.3.0 or newer
All the classes contain PHP documentation, so you can start by reading the API documention.
Example:
<?php
require_once('lib/Validate/Validator.class.php');
function save_student_score(array $params) {
$params = (new Validate\Validator(array(
'specs' => array(
'name' => array(
'type' => 'string',
'max_length' => 2,
'max_length' => 30,
),
'birthdate' => array(
'type' => 'string',
'regex' => '#^[0-3]\d/[01]\d/\d{4}$#', // expect dd/mm/yyyy
'after' => function(&$value) { // want yyyy-mm-dd
if (is_string($value) && preg_match('#^(\d{2})/(\d{2})/(\d{4})$#', $value, $matches)) {
$value = $matches[3] . '-' . $matches[2] . '-' . $matches[1];
}
},
'optional' => true,
),
'score' => array(
'types' => array('float', 'integer'),
'max_value' => 10,
'min_value' => 0,
),
),
)))->validate($params);
// Insert $params into database here.
}
$error = null;
try {
save_student_score($_POST);
}
catch (Validate\ValidationException $e) {
$error = $e->getMessage();
}
if ($error) {
// display error message.
}
else {
// display success message.
}
All of the code in this library is licensed under the MIT license as included in the LICENSE file