Light and extendable schema validation library

Overview

Light PHP validation library

For everyone who uses MongoDB or other NoSQL solution and cares about what client sends to his/her database and looking for validation library written in PHP. Volan validates array against given shema and provides you with full information about invalid nodes. Can be used with logging so you can see the whole validation process.

Build Status Coverage Status Scrutinizer Code Quality Latest Stable Version Total Downloads Latest Unstable Version License SensioLabsInsight

Installation


via Composer:

composer require serkin/volan dev-master

Usage


All you have to do is to specify _type field for each node. _type is a reference to a validation class

include 'vendor/autoload.php';

$schema = [
    'root' => [ // Schema must begins with 'root'
        'title' => [
            '_type' => 'required_string'
        ],
        'price' => [
            '_type' => 'number'
        ],
        'author' => [
            '_type' => 'string'
        ],
        'instock' => [
            '_type' => 'required_boolean'
        ],
        'info' =>  [
            '_type' => 'array',
            'isbn' => [
                '_type' => 'string'
            ],
            'pages' => [
                '_type' => 'number'
            ]
        ],
        'comments' => [
            '_type' => 'nested_array',
            'user_id' => [
                '_type' => 'required_number'
            ],
            'comment' => [
                '_type' => 'required_string'
            ]
        ]
    ]
];

$book = [
    'title' => 'The Idiot', // Cannot be omitted
    'instock' => true, // Cannot be omitted and has to be bool type
    'info' => ['isbn' => '978-0451531520'],
    //  'price' can be omitted but if present has to be numeric type 
    'comments' => [ // Nested array check nested elements
        [
            'user_id' => 1,
            'comment' => 'Good book',
            // 'extra_field' => 'bad field' 
            // By default if key not present in schema validation stops and returns false 
        ],
        [
            'user_id' => 2,
            'comment' => 'I like it'
        ]
    ]
];

$validator = new \Volan\Volan($schema);
$result = $validator->validate($book);

// if $result->isValid() === false you can get full information about invalid node
var_dump($result->getErrorInfo());

Predefined validators

Strings

  • string: string
  • required_string: string that has to be present

Arrays

  • array: array
  • required_array: array that has to be present
  • nested_array: array with nested arrays
  • required_nested_array: array with nested arrays has to be present

Bool

  • boolean: boolean
  • required_boolean: boolean that has to be present

Numbers

  • number: int or float
  • required_number: int or float that has to be present

Custom validators

If you need extra validators you can create them extending \Volan\Validator\AbstractValidator class

  • Create folder src/Volan/Validator in your library
  • Add your custom validator src/Volan/Validator/mongoid_validator.php. Example for mongoid validator:
namespace Volan\Validator;
class MongoidValidator extends AbstractValidator
{
    public function isValid($nodeData)
    {
        return ($nodeData instanceof \MongoId);
    }
}
  • Add autoload to composer.json
"autoload": {
        "psr-4": {
            "Volan\\Validator\\": "src/Volan/Validator/"
        }
    }

Usage with other libraries

If you want to use other validation libraries with Volan it is easy. Let's take a look how it works with Respect validation engine

namespace Volan\Validator;
use Respect\Validation\Validator as v;

class IntBetween10And20Validator extends AbstractValidator
{
    public function isValid($nodeData)
    {
        return v::int()->between(10, 20)->validate($nodeData);
        
    }
}

Tips

Allow extra keys in data

If you want allow extra keys in array you can define it in constructor

$validator = new \Volan\Volan($schema, $strictMode = false);

Allow required fields be omitted

In mongoDB when you update just several fields in collection you cannot pass validation cause required fields may be missing. You can tell validator consider all required validation as optional.

$validator = new \Volan\Volan($schema);
$validator->setRequiredMode(false);
$result = $validator->validate($book);

Logging

If you want see validation process set logger

$validator = new \Volan\Volan($schema);

$result = $validator->validate($book);
$result->getLog();

PSR compatible class names

You can use PSR compatible names for validation classes. Previous example with mongoid validation class can be rewritten like:

namespace Volan\Validator;

class MongoidValidator extends AbstractValidator
{
    public function isValid($nodeData)
    {
        return ($nodeData instanceof \MongoId);
    }
}

Here we changed mongoid_validator to MongoidValidator. Example with int_between_10_and_20_validator be rewritten to IntBetween10And20Validator

Relational structure

Let's imagine we have field in our book data

...
'categories' => [new \MongoId('111111111111111111111111'),new \MongoId('111111111111111111111112')]
...

and we want ensure that all elements not only instances of MongoId but actually present in our database. It is easy. Our validator will be look like: namespace Volan\Validator;

class ArrayOfMongoids extends AbstractValidator
{
    public function isValid($nodeData)
    {
        foreach($nodeData as $id) {
            if($id !instanceof \MongoId) || !$this->presentInCategoryCollection($id))
                return false;
            }
        }
        
        return true;
    }
    
    public function presentInCategoryCollection($id)
    {
        // Getting connection and so on

        $collection = $db->selectCollection('categories');
        return (bool)$collection->findOne(['_id' => $id]);
    }
    
}

now in schema we add

...
'categories' => ['_type' => 'array_of_mongoids']
...

Dependencies

  • PHP: >= 5.4

Contribution

Please see CONTRIBUTING for details.

Licence

The MIT License (MIT). Please see License File for more information.

Tests

phpunit

Or with Docker

docker run --rm -v "$PWD":/var/src/ serkin/php7 vendor/bin/phpunit --debug

Code style

docker run --rm -v "$PWD":/var/src/ serkin/php7 vendor/bin/php-cs-fixer fix src
You might also like...
One Line Validation, For CodeIgniter 4

One Line Validation (OLV) is a package made for CodeIgniter 4 to provide a fast and single line validation experience ideal for CDN and/or API services consuming the Validation System from CodeIgniter 4.

🔒 Laravel validation rule that checks if a password has been exposed in a data breach.
🔒 Laravel validation rule that checks if a password has been exposed in a data breach.

🔒 Laravel Password Exposed Validation Rule This package provides a Laravel validation rule that checks if a password has been exposed in a data breac

高性能的验证器组件(Validation),适用于 Hyperf 或 Laravel 框架,可获得数百倍的性能提升

验证器 简介 兼容 Hyperf/Laravel Validation 规则 部分场景可获得约 500 倍性能提升 验证器可多次复用不同数据,无状态设计 规则可全局复用 智能合并验证规则 安装 环境要求 PHP = 8.0 mbstring 扩展 ctype 扩展 安装命令 composer re

Extension for the Laravel validation class

Intervention Validation Intervention Validation is an extension library for Laravel's own validation system. The package adds rules to validate data l

Extra validation rules for dealing with images in Laravel 5.

Image-Validator Extra validation rules for dealing with images in Laravel 5. NOTE: As of Laravel version 5.2, there are now built-in validation rules

laminas-password-validator provides a validator for character-set based input validation.

laminas-password-validator laminas-password-validator provides a validator for character-set based input validation. Installation composer require pra

Laravel Validation Service

Laravel Validation Service Installation Add "prettus/laravel-repository": "1.1.*" to composer.json "prettus/laravel-validation": "1.1.*" Create a vali

🔒 Laravel validation rule that checks if a password has been exposed in a data breach.
🔒 Laravel validation rule that checks if a password has been exposed in a data breach.

🔒 Laravel Password Exposed Validation Rule This package provides a Laravel validation rule that checks if a password has been exposed in a data breac

PHP library to validate and convert ISBNs and EANs

biblys/isbn biblys/isbn can be used to: validate a string against the ISBN-10, ISBN-13 and EAN-13 formats convert an ISBN to ISBN-10, ISBN-13, EAN-13

Owner
Alexander Serkin
Alexander Serkin
Lightweight and feature-rich PHP validation and filtering library. Support scene grouping, pre-filtering, array checking, custom validators, custom messages. 轻量且功能丰富的PHP验证、过滤库。支持场景分组,前置过滤,数组检查,自定义验证器,自定义消息。

PHP Validate 一个简洁小巧且功能完善的php验证、过滤库。 简单方便,支持添加自定义验证器 支持前置验证检查, 自定义如何判断非空 支持将规则按场景进行分组设置。或者部分验证 支持在进行验证前对值使用过滤器进行净化过滤内置过滤器 支持在进行验证前置处理和后置处理独立验证处理 支持自定义每

Inhere 246 Jan 5, 2023
A powerful schema validator!

MetaYaml A [put your file type here] schema validator using [put another file type here] files. At the moment, file type can be Json, Yaml, or XML. It

Romaric Drigon 100 Sep 28, 2022
MetaYaml - A powerful schema validator

MetaYaml A [put your file type here] schema validator using [put another file type here] files. At the moment, file type can be Json, Yaml, or XML. It

Romaric Drigon 100 Sep 28, 2022
Valitron is a simple, elegant, stand-alone validation library with NO dependencies

Valitron: Easy Validation That Doesn't Suck Valitron is a simple, minimal and elegant stand-alone validation library with NO dependencies. Valitron us

Vance Lucas 1.5k Dec 30, 2022
[READ-ONLY] Validation library from CakePHP. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp

CakePHP Validation Library The validation library in CakePHP provides features to build validators that can validate arbitrary arrays of data with eas

CakePHP 39 Oct 11, 2022
An extensible validation library for your data with sane defaults.

Hird Hirds, also known as housecarls, was a gathering of hirdmen, who functioned as the king's personal guards during the viking age and the early mid

Asko Nõmm 13 Apr 23, 2022
FyreValidation is a free, open-source validation library for PHP.

FyreValidation FyreValidation is a free, validation library for PHP. Table Of Contents Installation Validators Rules Error Messages Installation Using

Elusive 0 Jan 15, 2022
File uploads with validation and storage strategies

Upload This component simplifies file validation and uploading. Usage Assume a file is uploaded with this HTML form: <form method="POST" enctype="mult

Brandon Savage 1.7k Dec 27, 2022
Abstracts HTTP request input handling, providing an easy interface for data hydration and validation

Linio Input Linio Input is yet another component of the Linio Framework. It aims to abstract HTTP request input handling, allowing a seamless integrat

Linio 41 Dec 12, 2021
Validation rules for Money and Currency

money-validation-laravel Validation rules for Money and Currency Installation composer require brokeyourbike/money-validation-laravel Usage Package us

Ivan Stasiuk 1 Oct 25, 2021