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.
Configuration
Optionally, the validation class can be configured through the global application configuration file, app/config/config.php. Define a section called 'validation', in which the following settings can be defined:
Variable |
Type |
Default |
Description |
no_errors |
string |
''
|
String to return if no validation errors were discovered. |
open_list |
string |
'<ul>'
|
String to be prepended to the list of errors. Usually this is some form of HTML to format the list. By default, it's formatted as an unordered list. |
close_list |
string |
'</ul>'
|
String to be appended to the list of errors. |
open_error |
string |
'<li>'
|
String to be prepended to each individual error message. |
close_error |
string |
'</li>'
|
String to be appended to each individual error message. |
quote_label |
boolean |
false
|
If true, and the label of the validated field contains spaces, the label will be enclosed in double quotes for enhanced readability. |
global_input_fallback |
boolean |
true
|
If true, and value is not found in input array, the value will fall back to Input::param. |
If one or more of these values are missing from the global configuration, the class will use the defaults as defined in this table.
Usage
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::forge();
// ... or name it
$val = Validation::forge('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::forge('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);
// Now add another field for gender, and require it to contain either "M" or "F".
$val->add('gender', 'Your gender')->add_rule('required')
->add_rule('match_collection', array('M', 'F'));
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 than strings. You can also not use the pipe symbol in your pattern when you use
the 'match_pattern' rule, as that is used to separate the defined rules.
// The same fields as the example above
$val = Validation::forge('my_validation');
$val->add_field('username', 'Your username', 'required');
$val->add_field('password', 'Your password', 'required|min_length[3]|max_length[10]');
$val->add_field('gender', 'Your gender', 'required|match_collection[M,F]');
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->error();
// 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);
Validation rules
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.
|
required_with |
$fieldname |
The field must be set if the field with the given $fieldname is set.
|
match_value |
$compare, $strict = 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.
Note: you can NOT use the pipe symbol (|) in your pattern when you're using short syntax, as that symbol is used to split the rules in the string.
|
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.
|
match_collection |
$collection = array(), $strict = false |
Will try to match the field against a collection of valid values, will be done using == unless 2nd parameter
is given as true (then === is used).
|
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_date |
$format, $strict = true |
Validates if the given input is a valid date format. If the $format parameter is given then
validates using specified format. Will check date strict (example, leap year) unless 2nd parameter is given as false.
|
valid_email |
(none) |
Validates if the given input is a valid email address.
|
valid_emails |
$separator (optional) |
Validates multiple email addresses separated by commas (or $separator).
|
valid_url |
(none) |
Validates if the given input is a valid URL.
|
valid_ip |
$flag (optional) |
Validates if the given input is a valid IP address. You can set 'ipv4' or 'ipv6' to $flag to check a specific IP address format.
|
numeric_min |
$min_val |
Tests whether the given input is a number that is greater than $min_val, it does
not check or cast the input to a numeric value so any non-numeric value will be considered
to be zero. Use the PHP function is_numeric to check that first.
|
numeric_max |
$max_val |
Tests whether the given input is a number that is smaller than $max_val. (see
note about non-numeric values with numeric_min rule)
|
numeric_between |
$min_val, $max_val |
Tests whether the given input is a number that is between than $min_val and $max_val. (see
note about non-numeric values with numeric_min rule)
Important: specified numbers are included in the range.
|
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. |
specials |
Allow alphabetical and special language characters. |
numeric |
Allow numeric characters. |
spaces |
Allow normal spaces. |
newlines |
Allow newline character. |
tabs |
Allow tabs. |
dots |
Allow dots. |
commas |
Allow commas. |
punctuation |
Allow dots, commas, exclamation marks, question marks, colons and semi-colons. |
dashes |
Allow dashes and underscores. |
singlequotes |
Allow single quotes. |
doublequotes |
Allow double quotes. |
quotes |
Allow single and double quotes. |
forwardslashes |
Allow forward slashes. |
backwardslashes |
Allow backward slashes. |
slashes |
Allow forward and backward slashes. |
brackets |
Allow open and close brackets. |
braces |
Allow open and close curly braces. |
utf8 |
Adds UTF8 modifier to regex. |
Extending the Validation class
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/myrules.php (for example)
// app/classes/myrules.php
class MyRules
{
// note this is a static method
public static function _validation_unique($val, $options)
{
list($table, $field) = explode('.', $options);
$result = DB::select(DB::expr("LOWER (\"$field\")"))
->where($field, '=', Str::lower($val))
->from($table)->execute();
return ! ($result->count() > 0);
}
// note this is a non-static method
public function _validation_is_upper($val)
{
return $val === strtoupper($val);
}
}
// and call it like:
$val = Validation::forge();
// Note the difference between static and non-static validation rules:
// Add it staticly, will only be able to use static methods
$val->add_callable('MyRules');
// Adds it non-static, will be able to use both static and non-static methods
$val->add_callable(new MyRules());
$val->add('username', 'Your username', array(), array('trim', 'strip_tags', 'required', 'is_upper'))
->add_rule('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::forge();
$val->add_model('Model_User');
Note:
You need the '_validation_' prefix for a method to be available in validation.
Note:
if you pass the class name as a string, the validation method must be defined as static. If the method is not static, you will have to pass an object instance as callable().
It can be useful to use Validation::active() and Validation::active_field() to get the currently active validation instance and field currently being validated, respectively.
For example, in the above you could do:
public static function _validation_unique($val, $options)
{
Validation::active()->set_message('unique', 'The field :label must be unique, but :value has already been used');
...
}