Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Introduction to Respect Validation Engine for PHP

In this article we will discuss about the Respect Validation. We will discuss the Respect Validation methods including type checking, comparing values, file checking, validating date and time etc.

Respect Validation is a perfect engine for validation created for PHP. It consists of almost 100 validators which are fully tested. It works on PHP 5.3+ and HHVM 3.3+ (HipHop Virtual Machine – It is open source virtual machine designed for executing the PHP written program. ). It includes number of validation methods such as type checking (array, string, numeric etc), comparing values and file checking, validating date and time, numeric values and checking the contents of strings, array and object.

Installation

From the above link, you can download two zip folders i.e. Loader and Respect. Later extract the downloaded files and keep in a root folder of your localhost. To validate the code, you require PHP version PHP 5.3+ and HHVM 3.3+.

OR

You can validate the code by installing the Composer by using following command:

  composer require respect/validation
  

Here we are going to use the first way i.e. directly keeping the folder Loader and Respect in the localhost server.

Features

Namespace Import

Namespace Import is used to include the external file names. In PHP, the aliasing is accomplished with the operator use.

The syntax can be written as shown below:

  use \Respect\Validation\Validator as v;
  

Simple Validation

Simple validation is used to handle validation process easily; it makes calls to APIs for the validation. It allows defining the more complex rules like checking database records.

The syntax can be written as shown below:

  $variable_name = john;
  v::string() -> validate($variable_name)
  

Chained Validation

It can validate the code in a chain format and also uses different validators in the same chained format.

The syntax can be written as shown below:

  $userValidator = v::digits()->notEmpty()->length(1,10)->positive()->validate('1234567890')
  

The above syntax validates digits with not empty whose length should be between 1 and 10 and the positive ( ) method is used to take values higher than zero.

Validating Object Attributes

Object attribute is an attribute that defines a property of an object, file or element. Object attributes can be validate in array keys or in single chain.

The syntax can be written as shown below:

Object validation for single chain:

  $dtt->name= John;
  $dtt->date= "d/m/Y";
  

Object validation in array keys:

  $dt=v::attributeName(‘name’)->date('Y-m-d')->validate($dtt);
  

Input Optional

Input is treated as optional in all validators and accepts the empty string input as valid.

The syntax can be written as shown below:

  v::digits()->notEmpty()->validate(' ');
  

Negating Rules

Negating is an operation that takes truth values, semantic values or proposition. It is usually identified in a truth function i.e. it takes value as true when it is defined false and vice versa. You can use v::not to negate any rule.

The syntax can be written as shown below:

  v:: not (v::int())-> validate(‘56321’)
  

Validator Reuse

The validators which are created can be reused anywhere. Just we have to remember the name of the validator.

The syntax can be written as shown below:

  $usernameValidator -> validate(‘John’); //false
  $usernameValidator -> validate(‘respect’) //true
  

Exception Types

There are three exception types in Respect\Validation.

· Respect\Validation\Exceptions\ExceptionInterface: This interface is implemented by all exceptions.

· Respect\Validation\Exceptions\ValidationExceptionInterface: This interface is extended from Respect\Validation\Exceptions\ExceptionInterface. The interface can also implement on all validation exception. It has one method getMainMessage( ) and it is called using check( ).

· Respect\Validation\Exceptions\NestedValidationExceptionInterface: This interface is extended from Respect\Validation\Exceptions\ValidationExceptionInterface. This interface has three methods i.e. getFullMessage( ), findMessages( ) and getGainMessages( ) and it is called using assert( ).

Informative Exceptions

Informative exception is used to give information of what exactly is going on and where it has gone wrong. Instead of validate( ) method, we are going to use assert( ) method for this.

The syntax can be written as shown below:

  use Respect\Validation\Exceptions\NestedValidationExceptionInterface;
  try{
         $usernameValidator -> assert(‘Your message to display when things go wrong’;)
  } catch (NestedValidationExceptionInterface $exception) {
         echo $exception-> getFullMessage();
  }
   

Getting Messages

To get messages you can use findMessages( ) method on custom or HTML form. The findMessages( ) returns messages as an array from the requested validators.

The syntax can be written as shown below:

  use Respect\Validation\Exceptions\NestedValidationExceptionInterface;
  try{
         $usernameValidator -> assert(‘Your message to display when things go wrong’;)
  } catch (NestedValidationExceptionInterface $exception) {
         var_dump($exception -> findMessages(array(‘alnum’, ‘length’, ‘noWhiteSpace’ )));
  } 
  

Custom Messages

The findMessages( ) method is used to customize for getting message as an array in front of the users. For template the variable {{name}} and {{input}} is available for all messages.

The syntax can be written as shown below:

  $errors = $exception->findMessages (array(
      'alnum'        => '{{name}} must contain only letters and digits',
      'length'       => '{{name}} must not have more than 15 chars',
      'noWhitespace' => '{{name}} cannot contain spaces'
  ));
  

Custom Rules

It is also possible to define your custom rules in the validation process.

The syntax can be written as shown below:

  v::with('My\\Validation\\Rules\\', true);
  v::alnum();
  

Validator Name

Validator name can be customized in the validation process as shown below.

The syntax can be written as shown below:

  v::date('Y-m-d')->between('1980-02-02', '2013-09-12')->setName('Member Since');
  

Zend/Symfony Validators

The validators are possible to reuse from other installed frameworks.

The syntax can be written as shown below:

  $hostValidator = v::zend('Hostname')->assert('mrbool.com');
  $timeValidator = v::sf('Time')->assert('22:00:05');
  

Validation Methods

The check( ) method is used to find an exception for error which is found at first and assert( ) method throws a complete validation report including the first error.

The syntax can be written as shown below:

  use Respect\Validation\Exceptions\ValidationExceptionInterface;
  try{
         $usernameValidator -> check(‘Your message to display when things go wrong’;)
  } catch (ValidationExceptionInterface $exception) {
         echo $exception-> getMainMessage();
  } 
  

Example

Following is a simple example of a Respect Validation code.

[Listing1. sample.php]

  <?php
  $loader = require ' Loader\library\Respect\Loader.php';
  spl_autoload_register($loader);
  use \Respect\Validation\Validator as v;
   
  date_default_timezone_set('Asia/Calcutta');
   
  $ojrtime=date('2015-06-23');
  echo "<h3>".$ojrtime;
  echo "<br>";
   
  $today_45=date('Y-m-d', strtotime("+45 days"));
  echo "45 days from today: ".$today_45."<br>";
   
  if(!v::date()->max($today_45,true)->validate($ojrtime))  //evaluate false value only because !
  {
         echo "Please select date within ".$today_45;
         echo "<br>";
  }
  else
  {
         echo "Done with date ".$ojrtime;
         echo "<br>";
  }
   
  $Time_1=date('g:i:s',strtotime("+1 hour"));
  echo "One hour from now: ".$Time_1;
  echo "<br>";
   
  $ortime=date('6:00:00');
  echo "$ortime";
  echo "<br>";
   
  if(!v::date()->min($Time_1,true)->validate($ortime))  
  {
         echo "Please choose after one hour of the current time ".date("g:i:s",strtotime($ortime));
         echo "<br>";
  }
  else
  {
         echo "Done with time ".$ortime;
  }
  ?>
  

Details of code:

  • The above code shows simple example of Respect Validation.
  • $loader = require ' Loader\library\Respect\Loader.php'; line is used to load the Loader.php file. The file Loader.php is a downloaded file present in the Loader folder which we have downloaded as mentioned in the installation step at the beginning.
  • spl_autoload_register($loader); line registers the given function as autoload.
  • use \Respect\Validation\Validator as v; line includes the external file names. These files are present in the folder name Respect which we had downloaded as mentioned in the installation step at the beginning.
  • date_default_timezone_set('Asia/Calcutta'); is used to set the default time zone by preferring the particular country name.
  • $ojrtime=date('2015-06-23'); is used to define the variable for date.
  • echo "<h3>".$ojrtime; line displays the output in h3 tag.
  • $today_45=date('Y-m-d', strtotime("+45 days")); line defines and store the date variable in $today_45.
  • date is an attribute name which is mentioned in the format of year/month/date.
  • strtotime("+45 days") displays the date after 45 days from the date as mentioned initially.
  • echo "45 days from today: ".$today_45."<br>"; line displays the date after 45 days from today.

  if(!v::date()->max($today_45,true)->validate($ojrtime))  {
         echo "Please select date within ".$today_45;
         echo "<br>";
  }
  else
  {
         echo "Done with date ".$ojrtime;
         echo "<br>";
  }
   
  

Here the code is used to validate the date in a chain format. By using if loop; we are checking the condition of the date is true or no.

  • $Time_1=date('g:i:s',strtotime("+1 hour")); line defines the time variable. The g:i:s is used to display the time in 12 hour format.
  • strtotime("+1 hour") is used to define the time after one hour from the present time.

  if(!v::date()->min($Time_1,true)->validate($ortime))  
  {
         echo "Please choose after one hour of the current time".date("g:i:s",strtotime($ortime));
         echo "<br>";
  }
  else
  {
         echo "Done with time ".$ortime;
  }
   
  

The above code is used to validate the time in the chain format and display message after checking if ( ) condition.

Output

  • Save the file astester.php.Place the PHPfile into the root directory of your localhost.
  • Open the web browser, typelocalhost/RespectValidation/tester.phpandyou would get the result as seen in the below screen.

Validators

Types

Description

Syntax

Arr

It is used to validate the input if it is an array.

array19

Bool

It is used to validate Boolean values (true or false).

array20

Date

It is used to validate the date and time.

   v::date()->validate(‘2013-06-03’)
   v::date()->validate(‘now’)
   

False

It is used to validate false value.

   v::false()->validate(false);   //true
   v::false()->validate(0);
   

Float

It represents the floating point number.

array23

Instance

It validates the input instance of the class.

   v::instance('DateTime')->validate(new   DateTime); 
   v::instance('Traversable')->validate(new   ArrayObject);
   

Int

It is used to validate the integer value of a variable.

array25

NullValue

It validates a variable with no value.

   v::nullValue()->validate(null);
   

Numeric

It validates any numeric values.

array27

Object

It validates the input object.

   v::object()->validate(new   stdClass);
   

String

It validates the sequence of characters. It should be written in quotes.

   v::string()->validate('hello');
   

True

It is used to validate true value.

   v::true()->validate(true);   
   v::true()->validate(1);
   

Type

It is used to validate the input type.

   v::type('bool')->validate(true);   
   v::type('callable')->validate(function   (){});
   

Xdigit

It is used to accept hexadecimal number.

array60

Generics

Description

Syntax

AlwaysInvalid

It returns invalid value always.

    v::alwaysInvalid()->validate($value);
   

AlwaysValid

It returns valid value always.

    v::alwaysValid()->validate($value);
   

Call

It is low level validator which uses function, methods or closure for the input to validate.

   v::call(array($Obj,'methodName'),v::int())->validate($InputValue);
   

Callback

It is wildcard validator that uses method, function and closure to validate the input.

   v::callback('is_int')->validate(5);
   

FilterVar

It is used to filter the variables.

   v::filterVar(FILTER_VALIDATE_EMAIL)->validate('john@bool.com');   
   v::filterVar(FILTER_VALIDATE_URL,FILTER_FLAG_PATH_REQUIRED)->validate('http://google.com');
   

Not

is used to negate the any rule.

   v::not(v::ip())->validate('foo');
   

Type

It is used to validate the input type.

   v::type('bool')->validate(true);   
   v::type('callable')->validate(function   (){}); 
   v::type('object')->validate(new   stdClass());
   

When

It is used to validate three parameters. When first parameter ($if) is validated, then it returns to second parameter ($then) for validation and if the first parameter ($if) is not validated, then it returns to third parameter ($else).

   v::when(v::int(),   v::positive(), v::notEmpty())->validate($input);
   

Comparing Values

Description

Syntax

Age

It is used to validate the ranges of years.

   v::age(10)->validate('10   years ago'); 
   v::age(18)->validate('1970-01-01');
   

Between

It validates the selected values within a range. It can be number, text or dates.

array46

Equals

It validates whether the two input values are equal or not.

   v::equals(50)->validate('50')
   

Max

It validates the highest value of several specific values.

   v::int()->max(10,   true)->validate(10);
   

Min

It validates the lowest value of several specific values.

   v::int()->min(7,   true)->validate(7);
   

Numeric

Description

Syntax

Between

It validates the selected values within a range. It can be number, text or dates.

array46

Bool

It is used to validate Boolean values (true or false).

array20

Even

It validates the even number.

   v::int()->even()->validate(2);
   

Float

It represents the floating point number.

array23

Int

It is used to validate the integer value of a variable.

array25

Multiple

It validates if there are multiple input values.

   v::int()->multiple(2)->validate(4);
   

Negative

It validates whether the negative value is less than zero or not.

   v::numeric()->negative()->validate(-5);
   

NotEmpty

It validates the given input value is not empty.

array74

Numeric

It validates on any numeric value.

array27

Odd

It validates the odd number.

   v::int()->odd()->validate(3);
   

PerfectSquare

It validates whether the input number is a perfect square or not.

   v::perfectSquare()->validate(16);
   

Positive

It validates whether the positive number is more than zero or not.

   v::numeric()->positive()->validate(5);
   

PrimeNumber

It validates a number which is divisible only by 1 and that number itself.

   v::primeNumber()   -> validate(5);
   

Roman

It validates the roman number.

   v::roman()->validate('II');
   

Xdigit

It is used to accept hexadecimal number

array60

String

Description

Syntax

Alnum

It validates the alphabet and numeric values from A-Z and 0-9.

   v::alnum()->validate('john   123');
   

Alpha

It validates the alphabets .

   v::alpha()->validate('john');
   

Between

It validates the selected values within a range. It can be number, text or dates.

array46

Charset

It validates group of characters.

   v::charset('ASCII')->validate('jack');
   

Cntrl

It validates the control character.

   v::cntrl()->validate("\n\r\t");
   

Consonant

It validates the consonant characters.

   v::consonant()->validate('rnmg');   
   

Contains

It validates contain for identical comparison.

array67

Digit

It validates the digit.

   v::digit()
   

EndsWith

It validates the contain present at the end of input.

array69

Graph

It validates the characters which are represented graphically.

   v::graph()->validate('L@#$%DW21;');
   

In

It validates contained input in a specific haystack.

array71

Length

It validates the length of the string.

array72

Lowercase

It validates the characters in lowercase.

   v::string()->lowercase()->validate('jack');
   

NotEmpty

It validates the given input value is not empty.

array74

NoWhitespace

It validates that there are no whitespace between the strings.

   v::noWhitespace()>validate("reading\nbooks");
   

Prnt

It validates the graphical character with whitespace.

   v::prnt()->validate('JHL5425$#@');
   

Punct

It validates the punctuation characters.

   v::punct()->validate(',   ; " ( { , &');
   

Regex

It validates the pattern of characters.

   v::regex('/[0-9]/')->validate('1');
   

Slug

It validates a word that describes about a thing or value in short.

   v::slug()->validate('describe-title');
   

Space

It validates the whitespace.

   v::space()->validate('    ');
   

StartsWith

It validates values which is present at the beginning of the input.

array81

Uppercase

It validates the characters in uppercase.

   v::string()->uppercase()->validate('JACK');
   

Version

It validates the version numbers.

   v::version()->validate('4.1.2');
   

Vowel

It validates the vowel character.

   v::vowel()->validate('aeiou');
   

Xdigit

It is used to accept hexadecimal number.

array60

Arrays

Description

Syntax

Arr

It is used to validate the input if it is an array.

array19

Contains

It validates contain for identical comparison.

array67

Each

It validates the current key and value pair from the array.

   $userName   = array(
         'validation' => '2010-01-01',
          'template'   => '2011-01-01',
          'relational' => '2011-02-05',
   );
    
   v::arr()->each(v::date())->validate($userName);
   

EndsWith

It validates the contain present at the end of an input.

array69

In

It validates whether the input is in specific haystack.

array71

Key

It validates the key array.

   $key   = array(
    'jack' => 'bar'
   );
    
   v::key('jack')->validate($key);
   

Length

It validates the length of the string.

array72

NotEmpty

It validates the given input value is not empty.

array74

StartsWith

It validates the contain present at the start in the input.

array81

Date and Time

Description

Syntax

LeapDate

It validates the leap date.

 
   v::leapDate('Y-m-d')->validate('2012-02-29');   

LeapYear

It validates the leap year.

   v::leapYear()->validate('2012');
   

MinimumAge

It validates the minimum age from the specified date.

   v::minimumAge(18)->validate('1991-09-12');
   

Group Validators:

Description

Syntax

AllOf

It validates all inner validators.

   v::allOf( v::int(),   v::positive())->validate(20);
   

NoneOf

It validates when no inner validators are validate.

   v::noneOf( v::int(),   v::float() )>validate('jack');
   

OneOf

It validates only one inner validator.

   v::oneOf(  v::int(), v::float() )->validate(9.6);
   

Regional:

Description

Syntax

CountryCode

It validates the ISO country code.

   v::countryCode()->validate('IND');
   

PostalCode

According to the specified country, it validates the postal code.

   v::numeric()->postalCode('IND')->validate('+91');
   

Tld

Top-level domain is validated.

   v::tld()->validate('com');
   

Files

Description

Syntax

Directory

It validates the directory of the file.

   v::directory()->validate(__DIR__);
   

Executable

It validates if the name of the file is executable.

   v::email()->executable('test.php');
   

Exists

It validates present files or directories.

   v::exists()->validate(__FILE__);
   

File

It validates only files.

   v::file()->validate(__FILE__);
   

Readable

It validates the files which are readable.

   v::readable()->validate('path/of   /file');
   

SymbolicLink

It validates the symbolic link path which is valid.

   v::symbolicLink()->validate('/path/of/symbolic/link');
   

Uploaded

It validates the file which was uploaded using HTTP POST.

   v::uploaded()->validate('/uploaded/file');
   

Writable

It validates the files which are writable.

   v::writable()->validate('/writable/file');
   

Banking

Description

Syntax

Bank

It validates the bank.

   v::bank("ind")->validate("356");
   

BankAccount

It validates the account of the bank of a specified bank.

   v::bankAccount("ind",   "356")->validate("25639");
   

Bic

It validates Identifier code of the bank of specified country.

   v::bic("ind")->validate("SBININBB776");
   

Others

Description

Syntax

Cnh (California-Nevada-Hawaii)

It validates the driver license of Brazilian.

   v::cnh()->validate('02650306461');
   

Cnpj (Cadastro Nacional da Pessoa Jurídica)

It validates the CNPJ number of Brazilian.

 
   v::cnpj()
    

Cpf (Cadastro de Pessoas Físicas )

It validates the CPF number of Brazilian.

   v::cpf()->validate('44455566820');
   

Domain

It validates the names of the domain.

   v::domain()->validate('google.com');
   

Email

It validates the email address.

   v::email()->validate('jack@bool.com');
   

HexRgbColor

It validates the color Hex RGB.

   v::hexRgbColor()->validate('#FFFFFF');
   

Ip

It validates the IP address.

   v::ip()->validate('192.168.0.1');
   

Json

It validates the data interchange format.

   v::json()->validate('{"jack":"bar"}');
   

MacAddress

It validates the network address.

   v::macAddress()->validate('00:11:22:33:44:55');
   

NfeAccessKey

It validates the Brazilian electronic invoice access key.

   v::nfeAccessKey()->validate('31841136830118868211870485416765268625116906')
   

Phone

It validates the phone number of valid digit.

   (+91)9874563210
   

Sf

You can use Symfony2 validator in Respect\Validation.

   v::sf('Time')->validate('24:00:00');
   

Url

It validates the URL path.

   v::url()->validate('http://google.com');
   

Zend

You can use Zend validator in Respect\Validation.

   v::zend('Hostname')->validate('google.com');
   

Yes/No

Description

Syntax

No

It validates if there is no value.

   v::no()->validate('N');
   

Yes

It validates if there is a value.

   v::yes()->validate('Y');
   

Conclusion

In this article, we discussed the feature guide of the Respect validation. It is very simple and straight forward PHP based validation library. The Source code of the example is attached with this article. We have also discussed the various types of validator present in the Respect Validation.

Links

Respect Validation official website

http://respect.li/Validation/



I''m a full stack developer with around 10+ yrs of experience. I enjoy writing technical articles on upcoming technical trends.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login