Install

To install envalid just run the following command in your projects root directory

composer require azi/envalid

Or add the following in your composer.json file


"require":{
     "azi/envalid":"^1.0"
}

Rules


Variables

Variable is very useful part of Envalid, where we can make our rules to take decision dynamically. a rule can accept multiple variables separated by : after the rule name
for example
...
'description' => 'length:>=:50' # in this example `>=` and `50` are our variables
...
To understand more how Envalid works with variables take a look at the length rule class


Arguments

Arguments are key value paired list of data that will be available to our Rule and Envalid class
Think of arguments as commandline options where we can ask the program to perform certain task or change the default behaviour.
Here is how you can pass arguments to a rule

$validator = new azi\Envalid();
$validator->validate($_POST, [
    'username' : 'required--message=Please provide a username',
    'password' : 'password:medium--key=value&key2=value2'
]);


Available Rules

Below is a list of all available validation rules


  1. Required
  2. Email
  3. Password
  4. Number
  5. Alnum
  6. Min
  7. Max
  8. Length
  9. Array
  10. Boolean
  11. IP
  12. Same
  13. File

Required

The field under the validation must have a value

Email

The field under the validation must be a valid email address

password:value

The field under the validation must be a password with in the provided strength
Variables
This rule accepts password strength as variable
Available Strengths
  • - normal (default)
  • - medium
  • - strong
Usage
...
'new_password' => 'password:strong'
...

Number

The field under the validation must have a numeric value

Alnum

The field under the validation must be Alpha Numeric

min:value

The field under the validation must be greater than or equal to the passed variable
Variables
This rule has one variable and that's required
Usage
...
'age' => 'min:18'
...

max:value

The field under the validation must be less than or equal to the passed variable
Variables
This rule has one variable and that's required
Usage
...
'age' => 'max:35'
...

length:operator:value

The field under the validation must meet the provided comparison, see the usage to understand how it works
Variables
This rule accepts two variables and one is required
This is how we construct the syntax : length:{operator}:{value} It alose can be like this length:{value}
Usage
...
'description' => 'length:=>:50', // string length must be greater than or equal to 50
'bio'         => 'length:<=:250', // string length must be less than or equal to 250
'code'        => 'length:6' // string length must be equal to 6
...

array:value

The field under the validation must be an array
Variables
This rule accepts a comma separated string as variable and it's optional
If we pass the csv to the rule it will require the field to contain those values : array:{csv_string}
Usage
...
'hobbies'           => 'array', // the field must be an array
'languages'         => 'array:php,javascript', // it must be an array and contains php and javascript
...

boolean:value

The field under the validation must be true or false
Variables
This rule accepts one optional variable,
We can pass `true` or `false` as variable, the field check the value accordingly. see the usage to understand how it works
Usage
...
'play_games'           => 'boolean', // the field must be boolean
'hate_animals'         => 'boolean:false', // it must be false
...

ip

The field under the validation must be formatted as IP address
Usage
...
'address' => 'ip'
...

same:value

The field under the validation have same value as the operand
Variables
This rule requires operand field name (must exists in the data passed to Envalid::validate method) as variable.
Usage
...
'confirm_password'  => 'same:password', // the value of `confirm_password` must be same as `password`
...

file:value

The field under the validation must be a file in required format
Variables
This rule accepts the file type as variable
Available file types
  • - image
  • - video
  • - doc
for more information check azi\Rules\File:16
Usage
...
'intro_video'      => 'file:video',
'profile_picture'  => 'file:image',
'cover_letter'     => 'file:doc',
...

Usage


Basic Example


$validator = new azi\Envalid();
$validator->validate($_POST, [
    'username'         => 'required',
    'email'            => 'required|email',
    'password'         => 'required|password:strong',
    'confirm_password' => 'same:password'
]);

if($validator->failed()) {
   return [
        'status'  => 'validation-failed',
        'message' => 'Please fill all the required fields correctly',
        'errors'  => $validator->getErrors()
    ];
}

Validating Files


$validator = new azi\Envalid();

// to validate files we will need to provide the $_FILES data to Envalid
$data = array_merge($_POST, $_FILES);


$validator->validate($data, [
    'bucket'  => 'required',
    'image'   => 'file:image',
]);

if($validator->failed()) {
   return [
        'status'  => 'validation-failed',
        'message' => 'Make sure you provided all the information correctly',
        'errors'  => $validator->getErrors()
    ];
}

Extend


Register a Rule

We can register our custom rules by passing the rule to addRule method on Envalid class

$validator = new azi\Envalid();
$validator->addRule('rule_name', 'Callable|Closure|azi\Rules\Contracts\RuleInterface');
See the next section if it feels confusing

Quick Custom Rules

As discussed earlier we can pass a closure or callable to the add rule method, which means if we want we can quickly register our custom rules,

$validator = new azi\Envalid();
$validator->addRule('recaptcha', function($field, $value, azi\Arguments $args){
    if(/* send a request to google to validate the recaptcha*/) {
        return true;
    }

    return "You failed to prove that your're a human :) ";
});

# lets validate our password reset form
$validator->validate($_POST, [
    'email'   => 'required|email',
    'captcha' => 'recaptcha' // We're using our custom rule
])

This feels super quick and easy isn't it? but if you have bunch of custom rules to work with this approach will not be ideal for you.
see the next section if you have extensive validation rules to work with

Rule Class


If you've extensive validation rules its recommended to extract the validation rules to their own classes,
The following code snippet explains how a Rule class looks like

<?php
use azi\Arguments;
use azi\Rules\Contracts\RuleInterface;

class RecaptchaRule implements RuleInterface
{

    /**
     * @param $field
     * @param $value
     * @param Arguments $args
     * @return boolean
     */
    public function validate( $field, $value, Arguments $args )
    {
        if(/* send a request to google to validate the recaptcha*/) {
            return true;
        }

        return false;
    }

    /**
     * The message if the validation fails
     *
     * @return string
     */
    public function message()
    {
        /* we can use {field} placeholder in the following string
           it will be replaced with the field label
        */
        return "You failed to prove that your're a human :) ";
    }

}
Our Rule class is ready now lets how we can register it with Envalid and use it

$validator = new azi\Envalid();
# This looks more clean isn't it ?
$validator->addRule('recaptcha', new RecaptchaRule());

# lets validate our password reset form
$validator->validate($_POST, [
    'email'   => 'required|email',
    'captcha' => 'recaptcha' // We're using our custom rule
])