JulienPHPFormValidation
Who is it for?
It’s a form validation library for people who, like me, don’t want/need to use a PHP framework.
Usage
Immediate Validation (Default)
include it:
include_once('validator.php');
instanciate it:
$validator = new Validator(array( 'first_name' => array( 'human_name' => "First Name", 'rules' => array('not_empty', array('min_length'=>2)) ), 'email' => array( 'human_name' => "Email", 'rules' => array('not_empty', array('format'=>'email')) ) ));
put this where you want to display the errors:
$validator->display_errors();
now to keep the user-entered values when people send the form, we need
this variable to be set:
$fields = $validator->get_fields();
and in each fields, we call the value() method like so:
<input type="text" name="first_name" <?php $fields['first_name']->value() ?> /></p>
For more details, look at form.php in the examples folder.
Deferred validation
Sometimes it’s nicer to define the validation rules earlier and proceed with the actual validation later on, with a sanitized version of the $_POST hash.
Here’s how you can do this:
$validator = new Validator(array( 'first_name' => array( 'human_name' => "First Name", 'rules' => array('not_empty', array('min_length'=>2)) ), 'email' => array( 'human_name' => "Email", 'rules' => array('not_empty', array('format'=>'email')) ) ), false); // <-- The validation will be deferred because of this argument
Then, later, when you have sanitized your POSTed data, you can perform the validation like this:
$validator->validate($sanitized_POST);
The rest is like the “Immediate Validation”.
Testing
To run the tests, you must include SimpleTest in test/validator.php .
You’ll probably also need to change the URL in the setUp method.