MFormValidator
Overview
MFormValidator is a PHP class that validates data sent through a form.
The validation is based on an easy-to-write configuration file that offers many possibilities.
You can validate all form data with PHP code as simple as:
$validator = mlib\utils\validator\MFormValidatorFactory::createFromFile(__DIR__."/path/to/validator.conf");
if(! $validator->run()){
echo $validator->getErrorMessage().'<br>';
echo 'Error on : '.$validator->getErrorField().'<br>';
}
and a "validator.conf" file (see below)
The configuration file
The configuration files for MFormValidator are MConfig files (see here).
They consist of a succession of blocks like this :
<form_field_name>
type = the_type
...
...
</form_field_name>
Common parameters, whatever the type :
Required :
- type : one of the values : string, enum, email, phone, integer, float, date, datetime, time, file, complex, custom
Optional :
* multi (bool) : if the field is multivalued
* required (bool) : if the field is required or not
* error : a generic error message if no other more precise message is returned
Depending on the specified type, a certain number of other directives will be required or optional.
string
You can use the string type to verify a "input type=text" or a "textarea"
Optional parameters :
* minlength :
* maxlength :
* regex :
You can use the type email to verify a "input type=text" or a "input type=email"
Optional parameters :
* regex :
integer
Optional parameters :
* min :
* max :
float
Optional parameters :
* min :
* max :
enum
The type enum serves to verify the value(s) of a select, checkboxes or radio buttons html.
Required parameters :
* options (config) : a configuration block for the values (see here)
date
Optional parameters :
* format : a format of date for a DateTimeInterface (see here)
- 'Y-m-d' (default)
* min : the minimum accepted date (today if not specified)
* max : the maximum accepted date (today + 1 year if not specified)
min and max can be dates in the format specified (Y-m-d by default) or well
- Y or Y ± N (with N an integer) : the 1st January (min) or the 31st December (max) of the year ± N years
- M or M ± N (with N an integer) : the 1st (min) or last (max) day of the month ± N months
- D or D ± N (with N an integer) : today ± N days
Exemples :
min = D # à partir d'aujourd'hui
max = D+365 # à l'horizon d'un an
min = Y-1 # du premier janvier de l'année précédente
max = Y+1 # au 31 décembre de l'anée suivante
datetime
Same as date
* format : 'Y-m-d H:i' (default)
time
Same as date
* format :'H:i' (default)
file
Allows to verify an uploaded file.
Optional parameters :
* file_types : the extensions of files accepted.
- one or several file extensions separated by "/"
A certain number of system verifications are also made which allow to know the cause in case of failure.
complex
The type complex allows to verify several fields linked between them.
A type complex can be multivalued (see type complex of MForm)
Required parameters :
* one or more configs of the fields that compose the combined field
custom
The type custom allows to make a custom verification of a form field (if no other type suits what you want to do).
To do this you will have to write a php class that inherits from MFormValidator, in which you will write a method charged of verifying the form field. You will indicate the name of this method in a parameter of the field configuration.
Required parameters :
* function : the name of the method to call to verify the field
The "options" block for the enum type
The "options" block must contain the "type" parameter which can take one of two values:
* constant: the list of options is always the same. It must be specified in the block (see below)
* custom: the list of options is dynamic. It will be specified at runtime using the setCustomOptions method (see below). This method is useful when the enumeration items (enum type) are stored in a database, for example.
If the type is "constant", it must then specify the following parameter :
* values : the values of the options separated by "/" (Ex : 1/2/3)
Example of a select with constant options :
<le_nom_du_champ>
type = enum
<options>
type = constant
values = 1/2/3
</options>
error = la valeur transmise ne fait pas partie des valeurs autorisées
</le_nom_du_champ>
Example of an enum with dynamic options at execution :
<le_nom_du_champ>
type = enum
<options>
type = custom
</options>
error = la valeur transmise ne fait pas partie des valeurs autorisées
</le_nom_du_champ>
Example of using setCustomOptions :
$validator = mlib\utils\validator\MFormValidatorFactory::createFromFile(__DIR__."/path/to/validator.conf");
$values = $database->getValuesOrderByValues(); // for the example
$validator_options = array(
'my_enum_with_dynamic_options' => $values
// other options for other fields could be set here
);
$validator->setCustomOptions($validator_options);
$result = $validator->run();
The globalCheck() method
In a form, we may need to make cross verifications between the form fields. That is to say that depending on the value of a field, the value of another must respect certain criteria (two passwords for example).
There exists for this a special method : globalCheck($vars)
To implement this global verification, you must create a validator class that inherits from MFormValidator and redefine the method.
Example :
class PasswordFormValidator extends MFormValidator{
public function globalCheck($vars){
if($vars['password1'] != $vars['password2']){
$this->setErrorMessage("Vous n'avez pas saisi 2 fois le même mot de passe");
return false;
}
return true;
}
}
$validator = new PasswordFormValidator(__DIR__."/path/to/validator.conf");
$result = $validator->run();
$vars contains everything that has been sent (copy of $_POST)
The method must return true or false.
Error messages
For each field to be checked, it is recommended to add one or more error messages in the configuration file.
Without this, if the validator returns false, we will not be able to tell the user why.
So we can add the error option which will be a generic message not very precise :
<my_field>
type = xxxx
....
error = "An error has been detected on the field my_field"
</my_field>
But for each option (depending on the type), we can add messages adapted to the error by prefixing the criterion with error_.
Example :
<my_field>
type = integer
min = 10
max = 100
required
error = "An error has been detected on the field my_field"
error_type = "my_field must be an integer"
error_min = "my_field must be greater than or equal to 10"
error_max = "my_field must be less than or equal to 100"
error_required = "Please enter a value for my_field"
</my_field>
These options are not mandatory, but if nothing is defined, the getErrorMessage() method will not return anything. We will just have the indication of the field in error thanks to the getErrorField() method.
That's why it is recommended to define at least the error parameter, which will be returned if the message corresponding to the criterion that causes the error is not specified.