Validator is a nifty form validation library with a small footprint.
Brought to you by the fine folks at KRDS.
========================================================================
To validate a form, you’ll have define its validation rules first then run the validation.
Start by instantiating a Validator
object:
$validator = new Validator;
The methods below can be chained to $validator
.
A validation rule checks a field against an expected type, format, value, …
The list of rules available is given in Rules section below.
First, choose the field you want to apply the rules on:
$validator->field('field_name');
Then, add one or more rules:
$validator->rule(new \Validation\Required);
->rule(new \Validation\Email);
A same rule can be applied to multiple fields. It is called a global rule.
It is useful to avoid repeating the same rule, for example in the case of several fields are required.
A global rule will be applied to each field until calling endGlobalRule
function.
There are two type of rules: 'and' and 'or'.
An 'and' rule is applied to each field added after declaring it.
It is the default type of rule.
$validator->globalRule($rule);
An 'or' rule will pass if at least one of the fields added after declaring it passes it.
It is typically used with \Validation\Required
, when at least one of X fields must be filled (for example, at least the user landline or mobile phone number).
$validator->globalRule($rule, Validator::OPERATOR_OR, $message);
$message
is a required property. It is the user-facing message that will be returned if none of the fields pass the rule.
To end the latest global rule declared:
$validator->endGlobalRule();
To run the validation:
$validator->run($fields);
// returns `true` if the validation passed, `false` otherwise.
$fields
is an a list of field name
=> value
, such as $_POST
.
This method will return true
if the validation passed, false
otherwise.
To get the errors messages:
$validator->getErrors();
/* Returns an array:
[
"field_name" => "Error message",
"field_name" => "Error message",
"field_name" => "Error message",
"_common" => [
"Common error message",
"Common error message"
]
]
_common errors are errors that apply to the whole form.
*/
The following examples validates a simple user information form.
$validator = new Validator;
$validator->globalRule(new \Validation\Required)
->globalRule(new \Validation\LengthGreaterThan(3))
->field('firstname')
->field('lastname')
->endGlobalRule()
->field('email')
->rule(new \Validation\Email)
->field('dob')
->rule(new \Validation\Dob)
->endGlobalRule();
if( ! $validator->run($_POST))
print_r($validator->getErrors());
Language files are located in lang/ folder. To choose a language for error messages:
\Validation\i18n::setLanguage($language);
The following languages are currently supported:
- en: English (default)
- fr: French
Returns the error for a field as a FieldError
object.
Use $error->getMessage()
to get the error message.
If no error, returns null
.
$error = $validator->field('field_name')->getError();
echo $error->getMessage();
In some case, you might need to push some error messages manually.
-
Push an error for a field:
$validator->field('field_name')->error('MyField error message');
-
Push an error related to the whole form:
$validator->globalError('Global error message');
Clear the error of a field and set it as if the validation passed.
$validator->field('field_name')->clearError();
To know whether a field has been given and passed the validation.
$validator->field('field_name')->ok();
// return `true` if the field is NOT missing and the validation passed, `false` otherwise.
Validation rules are executed only if the field is present (that means, given on the array, it might be empty).
- If a field equals
null
, it is considered missing; - if a field equals "null" (as a string), it is considered empty.
This is typically useful if you are using any kind of API console which removes the empty fields before making the call.
Validates an alphanumeric string.
Validates a boolean value.
Can be: true
/ false
/ 1 / 0 / "1" / "0" / ""
Validates a date in YYYY-MM-DD HH:MM format.
Validates a date + hour in YYYY-MM-DD HH:MM format.
This validation rule has to be placed at the top of the rules declaration for a field. It will block the other validation rules in the stack if another field is missing of invalid.
This validation rule won’t generate an error message by default in case of failure.
It can be shown anyway if $displayable
param of Validator::run is set to
true`.
new \Validation\DependsOn($field)
$field
is the name of the field it depends on
Validates a field made of digits only.
Can be either of type string
or int
.
Validates an email address.
Validates a float value.
Can be either of type string
or int
.
The decimal separator can be either a point (.) or a comma (,).
Validates a value greater than another value. Can validate numbers or dates.
new \Validation\GreaterThan($number[, $type])
$number
is the number that should be the lowest$type
can be set to\Validation\GreaterThan::TYPE_DATE
to compare dates
Validates a value part of a pre-defined list.
new \Validation\InArray($list[, $ignore_case = false])
$list
: List of values the validated value should belong to$ignore_case
: If true, the case will be ignored for searching through the array
Validates a required but empty field.
Validates a length greater than a given length.
new \Validation\LengthGreaterThan($length)
$length
: Length for which the field must be greater than.
Validates a length lower than a given length.
new \Validation\LengthLowerThan($length)
$length
: Length for which the field must be lower than.
Validates a value lower than another value. Can validate numbers or dates.
new \Validation\LowerThan($number[, $type = \Validation\GreaterThan::TYPE_NUMBER])
$number
is the number that should be the greatest$type
can be set to \Validation\GreaterThan::TYPE_DATE` to compare dates
Validates a required and non-empty field.
Validates a required field.
Validates that the value has not been changed.
new \Validation\Unchanged($reference)
$reference
is the reference value to be checked against
You can give custom rules to validate a field.
$validator->rule(function($value, $values, $validator) {
/**
* Remove the parameters you won’t use
* (typically, only $value is interesting)
**/
if(isUsernameTaken($value))
throw new Exception('This username is already taken. Please choose another one.');
});
$value
is the value checked$values
is the list of all the values$validator
is theValidator
object
Public static function:
$validator->rule('CustomValidation::ruleName');
// Will call: CustomValidation::ruleName($value)
A PHP function that takes a single parameter can be given.
The validation will fail if the function returns a “falsy” value (empty, 0, false, null, …).
$validator->rule('is_scalar');
// Will call: is_scalar($value)