Validation Class
The Validation class helps you validate user input, if you want to create a form & its validation at
the same time use the Fieldset class instead.
To start validation you need to create an object, this can be the default object named "default" or
you can name it if you need multiple validation objects.
// Use default
$val = Validation::factory();
// ... or name it
$val = Validation::factory('my_validation');
After having it instantiated you can start adding fields to it. This works exactly like the when using
the Fieldset class, however here we'll only document the preferred usage.
$val = Validation::factory('my_validation');
// Add a field for username, give it the label "Your username" and make it required
$val->add('username', 'Your username')->add_rule('required');
// Now add another field for password, and require it to contain at least 3 and at most 10 characters
$val->add('password', 'Your password')->add_rule('required')
->add_rule('min_length', 3)
->add_rule('max_length', 10);
The first parameter of the add_rule() method can contain PHP native function names, any valid PHP
callback and Closures in addition to the provided validation methods. The method will get the value to
be validated as its first argument and any further arguments can be given to the add_rule() method.
We also provide a shorter syntax which is very limited in comparison. It will not accept array-callbacks,
closures or parameters other then strings.
// The same fields as the example above
$val = Validation::factory('my_validation');
$val->add_field('username', 'Your username', 'required');
$val->add_field('password', 'Your password', 'required|min_length[3]|max_length[10]');
Once all the fields have been added you can run your validation. This will default to $_POST input, but
can be extended and overwritten when given an input array.
// run validation on just post
if ($val->run())
{
// process your stuff when validation succeeds
}
else
{
// validation failed
}
// alternative to above, overwriting the username in post, password will still be sought in post
if ($val->run(array('username' => 'something')))
When validation is ran there are three methods available for information about the input:
// get an array of successfully validated fields => value pairs
$vars = $val->validated();
// get an array of validation errors as field => error pairs
$errors = $val->errors();
// get an array of the input that was validated, this merged the post & input given to run()
$input = $val->input();
// all these methods can also get just the value for a single field
$var = $val->validated('username');
Validation can also run partially, in that case even required fields are ignored when they're not in
POST or the input given to run(). One does this by setting the 2nd parameter of run to true.
// this will only validate the password when username isn't present in post
$val->run(array('password' => 'whatever'), true);
Note that all methods (even min_length) will also return true on empty input. To also require the field
you must add the rule "required" as well.
All these rules can be used like below:
// example normal usage with rule without and one with params
$val->add('email', 'Email address')->add_rule('match_value', 'me@mydomain.com', true)->add_rule('valid_email');
$val->add_field('email', 'Email address', 'match_value[me@mydomain.com,1]|valid_email');
Rules table
required |
(none) |
The field must be set and have been given something other than null,
false or empty string.
|
match_value |
$compare, $strickt = false |
The field input must match $compare, will be done using == unless 2nd parameter
is also given as true (then === is used).
|
match_pattern |
$pattern |
Will try to match the value against the given $pattern which must be a full PREG regex.
|
match_field |
$field |
Will try to match the field to the field with the given fieldname, the matching is done
using ===.
Important: you can only match against a field that was added before the
field this rule is added to.
|
min_length |
$length |
Tests whether the string contains at least $length's number of character.
|
max_length |
$length |
Tests whether the string contains no more than $length's number of character.
|
exact_length |
$length |
Tests whether the string has precisely $length's number of character.
|
valid_email |
(none) |
Validates if the given input is a valid email address.
|
valid_emails |
(none) |
Validates multiple email addresses separated by commas.
|
valid_url |
(none) |
Validates if the given input is a valid URL.
|
valid_ip |
(none) |
Validates if the given input is a valid IP.
|
numeric_min |
$min_val |
Tests whether the given input is a number that is greater than $min_val.
|
numeric_max |
$max_val |
Tests whether the given input is a number that is smaller than $max_val.
|
valid_string |
$flags = array('alpha', 'utf8') |
See below.
|
Valid string rule
Validates whether a string adheres to the conditions set by the $flags parameter. The accepted flags
are:
alpha |
Allow alphabetical characters. |
uppercase |
Used in combination with alpha to only allow uppercase characters. |
lowercase |
Used in combination with alpha to only allow lowercase characters. |
numeric |
Allow numeric characters. |
spaces |
Allow normal spaces. |
newlines |
Allow newline character. |
tabs |
Allow tabs. |
dots |
Allow dots. |
punctuation |
Allow dots, commas, exclamation marks, question marks, colons and semi-colons. |
dashes |
Allow dashes and underscores. |
utf8 |
Adds UTF8 modifier to regex. |
Error messages are set using a language file "validation.php" which is loaded automatically.
There are 2 ways of manipulating the error messages during validation.
// change a rule per validation object
$val->set_message('required', 'The field :label is required.');
// or per error
echo $val->errors('username')->get_message('The field :label must be filled out before auth is attempted.');
// Outputs "The field Your username must be filled out before auth is attempted." when validation for username
// failed, or nothing when not yet validated or validation succeeded.
As you may have noticed the error messages accept a couple of variables that are replaced by the
field's properties. Below is a list of the available variables:
:field |
Will be substituted by the field's name. |
:label |
Will be substituted by the field's label. |
:value |
Will be substituted by the field's value which could not be validated. |
:rule |
Will be substituted by the rule that failed. The included rules will be just their name,
others will be the string callback or classname:method (which will also be the key for which
you must add a validation rule if you want to). |
:param:1 |
Will be replaced by the first additional parameter's value, :param:2 will be the second,
etc. |
There are few approaches to extend the validation class:
1. To extend the core class like described in the Extending Core Classes
2. To create a class in app/classes/myvalidation.php (for example)
// app/classes/myvalidation.php
class Myvalidation {
public function _validation_unique($val, $options)
{
list($table, $field) = explode('.', $options);
$result = DB::select("LOWER (\"$field\")")
->where("$field", '=', MBSTRING ? mb_strtolower($val) : strtolower($val))
->from($table)->execute();
if($result->count() > 0)
return false;
else
return true;
}
}
// and call it like:
$val = Validation::factory();
$val->add_callable('myvalidation'); // here we add the class to load rules from
$val->add_field('username', 'Your username', 'trim|strip_tags|required|unique[users.username]');
3. Calling callbacks from a model. It works like a method described above, but we only need to call it in other way:
$val = Validation::factory();
$val->add_model('Model_User');
Note:
You need the '_validation_' prefix for a method to be used in validation.
To be written.