FuelPHP Validation library.
, (*1)
A flexible library to validate different kinds of data., (*2)
Simple usage
<?php
use Fuel\Validation\Validator;
// Create a new validator instance to play with
$v = new Validator;
// Set up our required validation rules
$v->addField('name', 'User Name')
->required()
->addField('email', 'Email Address')
->required()
->email()
->addField('age', 'Current Age')
->number();
// Create some dummy data to validate
$data = array(
'name' => 'John',
'email' => 'john@doe.example',
'age' => 32,
);
// Perform the validation
$result = $v->run($data);
var_dump($result->isValid()); // true
var_dump($result->getValidated()); // List of all the fields that passed validation
Current validation rules
All core rule classes can be found under the Fuel\Validation\Rule
namespace., (*3)
- email - Checks for a valid email format
- ip - Checks for a valid IP address
- matchField - Compares the given field against another field being validated
- minLength - Checks if the value is >= a given value
- maxLength - Checks if the value is <= a given value
- number - Checks if the value is numeric or not
- numericBetween - Checks if a numeric value falls between an upper and lower band
- numericMax - Checks if the value is less than or equal to a given value
- numericMin - Checks if the value is greater than or equal to a given value
- regex - Checks if the value matches against a given regular expression
- required - Checks if the value exists in the data being validated
- url - Checks if the given value is a valid url or not
- date - Checks if the given value matches a given date format
- type - Checks if a value is a typeof or instanceof parameter(s)
- enum - Checks if a value is in an allowed list of values
- enumMulti - Checks if all values in an array are in an allowed list of values
- validator - For validating nested child models
Error messages
Messages can be retrieved from the result object after validatoin has been performed, (*4)
<?php
use Fuel\Validation\Validator;
// Create a new validator instance to play with
$v = new Validator;
// Set up our required validation rules
$v->addField('name', 'User Name')
->required()
->addField('email', 'Email Address')
->required()
->email()
->addField('age', 'Current Age')
->number();
// Create some dummy data to validate
$data = array(
'email' => 'john',
'age' => 'not a number',
);
// Perform the validation
$result = $v->run($data);
var_dump($result->isValid()); // false
var_dump($result->getValidated()); // array()
var_dump($result->getErrors()); // returns an array of all the error messages encountered
var_dump($result->getError('name')); // Returns the error message for the 'name' field
Custom messages
Messages can be set in two ways, directly on a rule instance or as part of the method chain., (*5)
use Fuel\Validation\Validator;
$v = new Validator;
$v->addField('name', 'User Name')
->required()
->setMessage('{label} is required, please enter a value');
Now when the required()
rule fails the custom message will be used., (*6)
There are several tokens that can be used as substitutions for various values. As in the example {label}
will be replaced
with the field's label and {name}
will be replaced with the field's name. (name
in the example above). Rules can also
provide other values, for instance NumericBetween
will allow you to use {upperBound}
and {lowerBound}
. Please refer to each rule
on the custom tokens provided., (*7)
If a token in a string is not found then it will simply be ignored and not replaced., (*8)
Default messages
It is possible to change the default message for a given rule by calling setGlobalMessage()
on the Validator
object.
After this method is called any rules created through the Validatator
via either magic methods or createRuleInstance()
will
have the specified message set by default., (*9)
use Fuel\Validation\Validator;
// Create a new validator instance to play with
$v = new Validator;
$v->setGlobalMessage('required', 'Sorry, my chum, but {label} is a required field and you did not enter anything');
Manually adding rules and rule overriding
As well as using the default core rules it is possible to dynamically add your own rules or override existing rules., (*10)
This is done by calling the addCustomRule()
function on a Validator
like so: $v->addCustomRule('myCustomRule', 'My\App\Rules\CustomRule')
.
If the class cannot be loaded for any reason an InvalidRuleException
will be thrown when the rule gets used., (*11)
The myCustomRule
rule is now available for use with the Validator
instance and can be called via the magic method syntax as well as the createRuleInstance()
function in Validator
., (*12)
<?php
use Fuel\Validation\Validator;
// Create a new validator instance to play with
$v = new Validator;
$v->addCustomRule('myCustomRule', 'My\App\Rules\CustomRule');
// Example of adding the new rule via magic method syntax
$v->addField('foobar')
->myCustomRule();
$instance = $v->getRuleInstance('myCustomRule');
var_dump($instance); // instance of My\App\Rules\CustomRule
Overriding existing rules
It is possible to replace existing rules simply by calling addCustomRule()
as in the previous example and passing the name of an existing rule, (*13)
<?php
use Fuel\Validation\Validator;
// Create a new validator instance to play with
$v = new Validator;
$v->addCustomRule('required', 'My\App\Rules\CustomRule');
// Example of adding the new rule via magic method syntax
$v->addField('foobar')
->required();
$instance = $v->getRuleInstance('required');
var_dump($instance); // instance of My\App\Rules\CustomRule
Nested validators
It is possible to use a validator itself as a rule for an entry in the data being validated. This allows child models to be validated along with the parent data.
This can be done using the Fuel\Validation\Rule\Validator
rule and can be nested as deeply as you desire., (*14)
<?php
$childValidator = new Validator();
$childValidator
->addField('test')
->maxLength(5);
$parentValidator = new Validator();
$parentValidator
->addField('child')
->validator($childValidator);
$parentValidator
->addField('foobar')
->required();
$result = $parentValidator->run([
'foobar' => 'test',
// 'child' contains our child model data and is validted by $childValidator
'child' => ['test' => '1234']
]);
Automatic Validator
population
Through the use of RuleProvider
classes it is possible to automatically create rule sets for a given Validator
this can be used to automatically create validation for any kind of object from forms to ORM models.
At the moment only one provider exists to serve as an example that creates rule sets from a config array. In the future Fieldset and ORM will provide their own providers., (*15)
The provider is used by creating a new Validator
, setting up your config array and then populating the Validator
., (*16)
<?php
use Fuel\Validation\Validator;
use Fuel\Validation\RuleProvider\FromArray;
// The key is the name of the field that has a value of an array containing the rules
$config = array(
'name' => array(
'required', // Rules with no parameters can be specified like this
),
'email' => array(
'required',
'email', // Make sure this is a valid email address
),
'age' => array(
'number',
'numericMin' => 18, // Make sure the value is 18 or greater
),
// The exact parameters for each rule are documented with the rule itself and can differ between rules.
);
$v = new Validator;
$generator = new FromArray;
$generator->setData($config)->populateValidator($v);
// $v is now populated with the fields and rules specified in the config array.
The RuleProvider
s will also be aware of custom rules that are added to the Validator
that they are passed., (*17)
<?php
use Fuel\Validation\Validator;
use Fuel\Validation\RuleProvider\FromArray;
$config = array(
'name' => array(
'myCustomRule',
),
);
$v = new Validator;
$v->addRule('myCustomRule', 'My\App\Rules\CustomRule');
$generator = new FromArray;
$generator->setData($config)->populateValidator($v);
You can also add a config with your custom structure., (*18)
<?php
use Fuel\Validation\Validator;
use Fuel\Validation\RuleProvider\FromArray;
// The key is the name of the field that has a value of an array containing the rules
$config = array(
'name' => array(
'label' => 'Name'
'validation' => array(
'required',
),
),
'email' => array(
'label' => 'Email address',
'validation' => array(
'required',
'email',
),
),
'age' => array(
'label' => 'Age',
'validation' => array(
'number',
'numericMin' => 18,
),
),
);
$v = new Validator;
// First parameter: label key, default: disabled
// Second parameter: rules key, default: rules
$generator = new FromArray(true, 'validation'); // same as new FromArray('label', 'validation');
$generator->setData($config)->populateValidator($v);
// $v is now populated with the fields and rules specified in the config array.