DataValidator – php class to validate data

Whenever I was involved in a php project, I felt that something that was really efficient to do any kind of data validation was missing Something that was effectively tested and approved and that allowed me to reuse code and mainly, that was adaptable to any type of system.

It was with this in mind that I took the free hours of last December to implement a data validation class (which I called DataValidator ). And to help the development community around the world, I’m making it available on GitHub ( https://github.com/rafaelwendel/DataValidator ).In this post I will show you how easy it is to incorporate and use the DataValidator class in your project and how to do the validations.Well, the first thing to do is download the class. You can do this via the github link I passed above or by cloning the class through your git bash.

$ git clone https://github.com/rafaelwendel/DataValidator.git

Validating data with the DataValidator

Now let’s instantiate the class and do the first validation. Imagine that in a register, the name attribute cannot be empty and it requires a minimum of 3 characters to be saved

1
2
3
4
5
6
7
8
ini_set('default_charset','UTF-8');    
include 'DataValidator.php';
 
$validate = new Data_Validator();
 
$validate->set('name1', 'Rafael')->is_required()->min_length(3); //validated
$validate->set('name2', '')->is_required()->min_length(3); //not validated
$validate->set('name3', 'Ra')->is_required()->min_length(3); //not validated

Note that only names with more than 3 characters are validated!

It is common for us to have to validate several fields at once. And that is why in  DataValidator, the validator methods always return the instance itself, so we can chain the validations and save lines of code.

1
2
3
4
5
6
7
8
ini_set('default_charset','UTF-8');    
include 'DataValidator.php';
 
$validate = new Data_Validator();
 
$validate->set('name', 'Rafael')->is_required()->min_length(3)
         ->set('email', 'rafaelwendel@hotmail.com')->is_email()
         ->set('age', 26)->min_value(18);

To perform the validation of all the data we pass for analysis, just execute the Boolean method validate().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
ini_set('default_charset','UTF-8');    
include 'DataValidator.php';
 
$validate = new Data_Validator();
 
$validate->set('name', 'Rafael')->is_required()->min_length(3)
         ->set('email', 'rafaelwendel@hotmail.com')->is_email()
         ->set('age', 26)->min_value(18);
if($validate->validate()){
     //All fields have been validated
}
else{
     //Some data has not been validated
}

Capturing, customizing and displaying validation errors

To catch validation errors, the get_errors() method returns an array of all errors that occurred during validation. If you want to catch a specific error, just pass the field name as a parameter.

1
2
3
4
5
6
7
8
9
10
ini_set('default_charset','UTF-8');    
include 'DataValidator.php';
 
$validate = new Data_Validator();
 
$validate->set('name', 'Ra')->min_length(3);
$validate->set('email', 'something')->is_email();
 
$errors = $validate->get_errors(); //Returns an array with all errors
$error_name = $validate->get_errors('name'); //Returns only errors that occurred in validating the "name" field

The get_errors () method returns an array whose index is the field name itself and its values ​​are each error referring to that field. However, we have the option to change the names of the indexes to something more suggestive and that will help out there when it comes to showing these errors to the user. For this we can define a prefix and a suffix for the name of the array index with the define_pattern method ($prefix, $sufix) .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
ini_set('default_charset','UTF-8');
include 'DataValidator.php';</p>
$validate = new Data_Validator();
 
/*I define a prefix for the error index
So the error array for the name field will look like this: $errors['error_name'] = 'The name field is required'
*/
$validate->define_pattern('error_', '');
 
$validate->set('name', 'Ra')->min_length(3);
$validate->set('email', 'something')->is_email();
 
$errors = $validate->get_errors(); //Returns an array with all errors
 
echo $errors['error_name'][0] . '<br />'; // Exibe: O campo nome deve conter ao mínimo 3 caracter(es) (pt-BR)
echo $errors['error_email'][0]; // Exibe: O email something não é válido (pt-BR)

Remembering that it is possible to use prefix and suffix or just one of them.

Now see a complete example of validation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
ini_set('default_charset','UTF-8');    
include 'DataValidator.php';
 
$validate = new Data_Validator();
 
/* Defino um prefixo para o índice do array de erros */
$validate->define_pattern('error_');
 
$validate->set('name', 'Rafael')->is_required()->min_length(3)
         ->set('email', 'rafaelwendel@hotmail.com')->is_email()
         ->set('age', 26)->min_value(18)
         ->set('url', 'http://www.rafaelwendel.com')->is_url();
 
if($validate->validate()){
     echo 'All data has been successfully validated';
}
else{
     $erros = $validate->get_errors();
     foreach ($errors as $error){ //Cycles through all errors
         foreach ($error as $err){ //Cycles through each error in the specific field
             echo '<p>' . $err . '</p>';
         }
     }
}

In this example, all fields will be validated. Perform simulations with data that does not pass validations.

And that’s it. In future posts I will show more features of this class.

I am open to criticism and suggestions for anyone who wants to contribute to this project.

The following is a list of all validator methods available in the class (so far).

  • is_required
  • min_length
  • max_length
  • between_length
  • min_value
  • max_value
  • between_values
  • is_email
  • is_url
  • is_slug
  • is_num
  • is_integer
  • is_float
  • is_string
  • is_boolean
  • is_obj
  • is_arr
  • is_equals
  • is_not_equals
  • is_cpf
  • is_cnpj
  • contains
  • not_contains
  • is_lowercase
  • is_uppercase
  • is_multiple
  • is_positive
  • is_negative
  • is_date
  • is_alpha
  • is_alpha_num
  • no_whitespaces

Hugs!!!

Holds a university degree in Information Systems, a postgraduate degree in Database Systems and a master's degree in Education with a focus on Sociocommunity Technologies. He works as a professor of technical and technological education at the Federal Institute of Education, Science and Technology of São Paulo, teaching subjects in the areas of programming, database, project development and software engineering.

Posts relacionados

Leave a Reply

Your email address will not be published.