Validation

Introduction

To learn about Kiaan's powerful validation features, let's look at a complete example of validating a form and displaying the error messages back to the user. By reading this high-level overview, you'll be able to gain a good general understanding of how to validate incoming request data using Kiaan:

Validating data

You can validating data with Validator::validate or validate helper function.

$validation = Validator::validate(input()->all(), [
  'name' => 'required|min:2',
  'email' => 'required|email',
]);

if ($validation->fails()) {
  return false;
} else {
  return true;
}

Attribute Alias

By default we will transform your attribute into more readable text. But you can set it anything you want.

$validation = validate(input()->all(), [
  'name:Name' => 'required|string|min:2',
  'email:Email' => 'required|email',
]);

Custom Validation Message

Before register/set custom messages, here are some variables you can use in your custom messages:

  • :attribute: will replaced into attribute alias.

  • :value: will replaced into stringify value of attribute. For array and object will replaced to json.

$validation = validate(input()->all(), [
  'name:Name' => 'required|string|min:2',
  'email:Email' => 'required|email',
], [
   'required' => ':attribute must be filled',
   'age:min' => 'Age is less than required'
]);

Working with Error Message

Errors messages are collected, that you can get it using errors() method.

$errors = $validation->errors();

Get all messages as flatten array.

$messages = $errors->all();
// [
//     'Email is not valid email',
//     'Password minimum 6 character',
//     'Password must contains capital letters'
// ]

$messages = $errors->all('<li>:message</li>');
// [
//     '<li>Email is not valid email</li>',
//     '<li>Password minimum 6 character</li>',
//     '<li>Password must contains capital letters</li>'
// ]

Get only first message from all existing keys.

$messages = $errors->firstOfAll();
// [
//     'email' => Email is not valid email',
//     'password' => 'Password minimum 6 character',
// ]

$messages = $errors->firstOfAll('<li>:message</li>');
// [
//     'email' => '<li>Email is not valid email</li>',
//     'password' => '<li>Password minimum 6 character</li>',
// ]

Argument $dotNotation is for array validation. If it is false it will return original array structure, if it true it will return flatten array with dot notation keys.

$messages = $errors->firstOfAll(':message', false);
// [
//     'contacts' => [
//          1 => [
//              'email' => 'Email is not valid email',
//              'phone' => 'Phone is not valid phone number'
//          ],
//     ],
// ]

$messages = $errors->firstOfAll(':message', true);
// [
//     'contacts.1.email' => 'Email is not valid email',
//     'contacts.1.phone' => 'Email is not valid phone number',
// ]

Get first message from given key. It will return string if key has any error message, or null if key has no errors.

if ($emailError = $errors->first('email')) {
    echo $emailError;
}

Check if key has errors.

if ($errors->has('email')) {
    return false;
}

Get all messages grouped by it's keys.

$messages = $errors->list();
// [
//     'email' => [
//         'Email is not valid email'
//     ],
//     'password' => [
//         'Password minimum 6 character',
//         'Password must contains capital letters'
//     ]
// ]

Or get all messages for one key.

$messages = $errors->list();

Get count messages.

$count = $errors->count();

Getting Validated, Valid, and Invalid Data

For example you have validation like this:

$validation = validate([
    'title' => 'Lorem Ipsum',
    'body' => 'Lorem ipsum dolor sit amet ...',
    'published' => null,
    'something' => '-invalid-'
], [
    'title' => 'required',
    'body' => 'required',
    'published' => 'default:1|required|in:0,1',
    'something' => 'required|numeric'
]);

You can get validated data, valid data, or invalid data using methods in example below:

$validatedData = $validation->validatedData();
// [
//     'title' => 'Lorem Ipsum',
//     'body' => 'Lorem ipsum dolor sit amet ...',
//     'published' => '1' // notice this
//     'something' => '-invalid-'
// ]

$validData = $validation->validData();
// [
//     'title' => 'Lorem Ipsum',
//     'body' => 'Lorem ipsum dolor sit amet ...',
//     'published' => '1'
// ]

$invalidData = $validation->invalidData();
// [
//     'something' => '-invalid-'
// ]

Available Rules

Click to show details.

required

required_if:another_field,value_1,value_2,...

required_unless:another_field,value_1,value_2,...

required_with:field_1,field_2,...

required_without:field_1,field_2,...

required_with_all:field_1,field_2,...

required_without_all:field_1,field_2,...

uploaded_file:min_size,max_size,extension_a,extension_b,...

mimes:extension_a,extension_b,...

default/defaults

email

uppercase

lowercase

json

alpha

numeric

alpha_num

alpha_dash

alpha_spaces

in:value_1,value_2,...

not_in:value_1,value_2,...

min:number

max:number

between:min,max

digits:value

digits_between:min,max

url

integer

boolean

ip

ipv4

ipv6

extension:extension_a,extension_b,...

array

same:another_field

regex:/your-regex/

date:format

accepted

present

different:another_field

after:tomorrow

before:yesterday

callback

nullable

unique:table, column, except

exists:table, column

Register/Override Rule

Another way to use custom validation rule.

For example, you want to create unique validator that check field availability from database.

First, lets create UniqueRule class:

<?php

use Kiaan\Security\Validator\Build\RuleBuild;

class UniqueRule implements RuleBuild
{
    protected $message = ":attribute :value has been used";

    protected $fillableParams = ['table', 'column', 'except'];

    protected $pdo;

    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    public function check($value): bool
    {
        // make sure required parameters exists
        $this->requireParameters(['table', 'column']);

        // getting parameters
        $column = $this->parameter('column');
        $table = $this->parameter('table');
        $except = $this->parameter('except');

        if ($except AND $except == $value) {
            return true;
        }

        // do query
        $stmt = $this->pdo->prepare("select count(*) as count from {$table} where {$column} = :value");
        $stmt->bindParam(':value', $value);
        $stmt->execute();
        $data = $stmt->fetch(PDO::FETCH_ASSOC);

        // true for valid, false for invalid
        return intval($data['count']) === 0;
    }
}

Then you need to register UniqueRule instance into validator like this:

Validator::rules([
    "unique" => new UniqueRule($pdo)
]);

Implicit Rule

Implicit rule is a rule that if it's invalid, then next rules will be ignored. For example if attribute didn't pass required* rules, mostly it's next rules will also be invalids. So to prevent our next rules messages to get collected, we make required* rules to be implicit.

To make your custom rule implicit, you can make $implicit property value to be true. For example:

<?php

use Kiaan\Security\Validator\Build\RuleBuild;

class YourCustomRule implements RuleBuild
{

    protected $implicit = true;

}

Last updated