Wern Ancheta

Adventures in Web Development.

Validating Data With Respect Validation

| Comments

Data validation is an absolute need for every PHP application. This protects your app from security breaches caused by malicious user input. Good thing there’s not a shortage of data validation libraries available for PHP. And most frameworks (if not all) have it as part of their core functionalities. In this tutorial, I’ll be walking you through using the Respect Validation library for PHP. It’s one of the most complete validation libraries that I’ve seen. It can validate a whole range of data types such as numbers, strings, arrays, objects, date, banking data, phone numbers, emails and others.

Installation

You can install the library through Composer.

1
composer require respect/validation

Once that’s done, include the vendor autoload file and give an alias to the Validation class. This allows you to use the alias instead of the actual class name.

1
2
3
4
5
<?php
require_once 'vendor/autoload.php';

use Respect\Validation\Validator as v;
?>

Validating Data

Now let’s take a look at some of the most common validators that you might want to use. All of the validators returns a boolean value, so if the data is valid it returns true, and if it’s not then it returns false. To validate a data, you first call the validator. Some validators allows you to specify the format in which the data should be and some does not. In cases that it allows you, simply pass in the format as the argument for that validator. Next, call the validate method and pass in the data that you want to validate.

Dates

To validate dates, you use the date validator. This accepts the date format as its argument. If you do not specify one, the default date format of Y-m-d is used.

1
2
3
4
<?php
$is_datevalid = v::date()->validate('2015-02-30'); //true
$is_datevalid = v::date('m-d-Y')->validate('2015-02-30'); //false
?>

If you haven’t noticed yet, one thing to note about date validation, is that it returns true even for a day that shouldn’t exist in a specific month. In the example above, the month february shouldn’t have a 30th day. If you use 32 or 33 for the day, it works fine since most of months have only 31 days.

Country Code

Validating country codes can be done by using the countryCode validator. On my testing, its only able to validate 2-character ISO country codes.

1
2
3
4
<?php
$is_validcountrycode = v::countryCode()->validate('PH'); //true
$is_validcountrycode = v::countryCode()->validate('PHL'); //false
?>

Between

The between validator allows you to validate if a specific value is between 2 values. It can validate strings, numbers and dates.

1
2
3
4
5
6
7
8
9
10
<?php
$is_between = v::string()->between('a', 'z')->validate('d'); //true
$is_between = v::string()->between('a', 'c')->validate('d'); //false

$is_between = v::int()->between(50, 90)->validate(20); //false
$is_between = v::int()->between(30, 60)->validate(31); //true

$is_between = v::date()->between('2015-03-25', '2015-04-30')->validate('2015-03-28'); //true
$is_between = v::date()->between('2015-07-12', '2015-10-30')->validate('2015-03-01'); //false
?>

Length

To validate if a string or array matches a specific length between a minimum and a maximum value, you can use the length validator. You can specify either of the minimum and maximum values if you don’t want to be specific.

1
2
3
4
5
6
7
<?php
$is_length = v::string()->length(10, 20)->validate('my-username'); //true
$is_length = v::string()->length(10, 20)->validate('my'); //false

$is_length = v::arr()->length(5, null)->validate(array('abc', 'def', 'ghi')); //false
$is_length = v::arr()->length(null, 3)->validate(array('abc', 'def', 'ghi')); //true
?>

Min and Max

The min and max validators allows you to check if an integer or date value is within the minimum or maximum value that you specify.

1
2
3
4
5
6
7
<?php
$is_min = v::int()->min(100)->validate(25); //false 
$is_min = v::int()->min(1)->validate(2); //true 

$is_max = v::date()->max('2015-07-27')->validate('2015-03-12'); //true 
$is_max = v::date()->max('2015-06-13')->validate('2015-08-29'); //false 
?>

Numbers

You can validate number values using the numeric, digit, and int validators. numeric is the generic number validator, it can accept integer, double or float values and even negative numbers. digit accepts whitespaces between integer values but it doesn’t accept float or double values. int accepts only integer values.

1
2
3
4
5
6
7
8
9
10
<?php
$is_numeric = v::numeric()->validate('55'); //true 
$is_numeric = v::numeric()->validate('99.9'); //true

$is_numeric = v::digit()->validate('45 3 330'); //true
$is_numeric = v::digit()->validate('7.9'); //false

$is_int = v::int()->validate('8.2'); //false
$is_int = v::int()->validate('709'); //true
?>

Domain

Domain names can be validated using the domain validator.

1
2
3
4
<?php
$is_domain = v::domain()->validate('github.com'); //true
$is_domain = v::domain()->validate('google.com.ph'); //true
?>

Bank

Bank information can also be validated. Currently, you can only validate bank accounts and bank identifier codes for Germany. And you have to install the bav Composer package to do that:

1
composer require malkusch/bav

Here are a few examples:

1
2
3
4
5
6
7
<?php
$is_bankaccount = v::bankAccount("de", "70169464")->validate("1112"); //true
$is_bankaccount = v::bankAccount("de", "70169464")->validate("1234"); //false

$is_bankaccount = v::bic("de")->validate("VZVDDED1XXX"); //true
$is_bankaccount = v::bic("de")->validate("VZVDDED1"); //true
?>

Alpha

If you want to restrict a string to only have letters, you can use the apha validator.

1
2
3
4
<?php
$is_alpha = v::alpha()->validate('abc 123'); //false
$is_alpha = v::alpha()->validate('abc def'); //true
?>

Alnum

You can validate alphanumeric characters (numbers and letters) using the alnum validator. You can group it

1
2
3
4
5
6
<?php
$is_alnum = v::alnum()->validate('batman 123'); //true
$is_alnum = v::alnum()->lowercase()->validate('batman 123'); //true
$is_alnum = v::alnum()->uppercase()->validate('batman 123'); //false
$is_alnum = v::alnum()->notEmpty()->validate('batman 123'); //true
?>

Email

Email addresses are validated using the email validator.

1
2
3
4
<?php
$is_email = v::email()->validate('not'); //false
$is_email = v::email()->validate('email@gmail.com'); //true
?>

Phone

Phone numbers that have 7, 10 or 11 digits in them can be validated.

1
2
3
4
<?php
$is_phone = v::phone()->validate('(072) 242 8084'); //true
$is_phone = v::phone()->validate('+639111111111'); //true
?>

Required

To set a specific data as required, you use the notEmpty validator.

1
2
3
4
<?php
$is_required = v::isNotEmpty()->validate(''); //false
$is_required = v::isNotEmpty()->validate('im not empty'); //true
?>

Chaining

As you have seen earlier, you can combine different validators together. Here are a few examples:

1
2
3
4
<?php
$is_alnum = v::alnum()->notEmpty()->validate('superman 456'); //true
$is_alnum = v::email()->notEmpty()->lowercase()->validate('superman456@gmail.com'); //true
?>

Validating an Array of Data

To validate an array of data or a form, you need to setup the rules for each field and add them in an array. You then loop through each item in the array and validate them one by one. In the example below, the check method is used instead of the validate method. This is because the validate method only returns a boolean value and not the actual error message. While the check method returns an exception which you can then get by calling the getMainMessage method in the exception that was returned. Lastly, use break to break the execution of the foreach loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
$rules = array(
    'username' => v::string()->lowercase()->length(10, 20)->notEmpty()->setName('username'),
    'email' => v::email()->notEmpty()->setName('email'),
    'phone_number' => v::phone()->notEmpty()->setName('phone number')
);

$data = array(
    'username' => 'wernancheta',
    'email' => 'myemail@gmail.com',
    'phone_number' => '111'
);

foreach($data as $key => $value){

    try{
        $rules[$key]->check($value);
    } catch (\InvalidArgumentException $e) {
        echo $e->getMainMessage();
        break;
    }

}
?>

Conclusion

That’s it! In this tutorial you’ve learned how to use the Respect Validation library for PHP. Be sure to check out the official docs if you want to learn more. If you’re using Laravel, you might want to check out this article on Sitepoint: Validating your data with Respect Validation.

Comments