All Projects → selective-php → validation

selective-php / validation

Licence: MIT license
A validation library for PHP that uses the notification pattern

Programming Languages

PHP
23972 projects - #3 most used programming language

Projects that are alternatives of or similar to validation

validator
Yii validator library
Stars: ✭ 47 (+74.07%)
Mutual labels:  validator
naija-phone-number
A fast minimal module to validate Nigerian mobile phone numbers using Regular Expressions.
Stars: ✭ 43 (+59.26%)
Mutual labels:  validator
persianize-node
Persianize is set of nodejs tools for validating and converting data to correct Persian.
Stars: ✭ 13 (-51.85%)
Mutual labels:  validator
KValidation
Validation library. Fluent syntax in Java, mini DSL in Kotlin
Stars: ✭ 20 (-25.93%)
Mutual labels:  validator
validate-framework
validate-framework:一款轻量、无依赖的 JavaScript 验证组件
Stars: ✭ 55 (+103.7%)
Mutual labels:  validator
schema
SpaceAPI JSON schema files.
Stars: ✭ 20 (-25.93%)
Mutual labels:  validator
max-validator
Advanced validation library for Javascript & React | Inspired by laravel validation
Stars: ✭ 29 (+7.41%)
Mutual labels:  validator
bpmnlint
Validate BPMN diagrams based on configurable lint rules.
Stars: ✭ 82 (+203.7%)
Mutual labels:  validator
govalidators
struct 验证器,内置大部分常用验证,可自定义
Stars: ✭ 56 (+107.41%)
Mutual labels:  validator
laravel-vatvalidator
Package to validate a vat id via the api of the european union (vies)
Stars: ✭ 15 (-44.44%)
Mutual labels:  validator
SheenValidator
Android library to make form validation easier
Stars: ✭ 29 (+7.41%)
Mutual labels:  validator
twig-translation
A Twig Translation Extension
Stars: ✭ 15 (-44.44%)
Mutual labels:  slim4
wily
Build Node.js APIs from the command line (Dead Project 😵)
Stars: ✭ 14 (-48.15%)
Mutual labels:  validator
typepy
A Python library for variable type checker/validator/converter at a run time.
Stars: ✭ 16 (-40.74%)
Mutual labels:  validator
wallet-address-validator
Useful library for validation of Bitcoin, Litecoin, Ethereum and other cryptocoin addresses
Stars: ✭ 240 (+788.89%)
Mutual labels:  validator
romans
A Simple PHP Roman Numerals Library
Stars: ✭ 40 (+48.15%)
Mutual labels:  validator
ird-nz
Checksum validator for New Zealand's IRD/GST number.
Stars: ✭ 15 (-44.44%)
Mutual labels:  validator
UE4-BUIValidator
UE4 UI Texture Validator Plugin
Stars: ✭ 48 (+77.78%)
Mutual labels:  validator
denetmen
useful micro check library for Crystal Language.
Stars: ✭ 23 (-14.81%)
Mutual labels:  validator
crystal-validator
💎 Data validation module for Crystal lang
Stars: ✭ 23 (-14.81%)
Mutual labels:  validator

Validation

A validation library for PHP that uses the notification pattern.

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads

Table of contents

Requirements

  • PHP 7.2+ or 8.0+

Installation

composer require selective/validation

Usage

A notification is a collection of errors

In order to use a notification, you have to create the ValidationResult object. A ValidationResult can be really simple:

<?php

use Selective\Validation\Exception\ValidationException;
use Selective\Validation\ValidationResult;

$validationResult = new ValidationResult();

if (empty($data['username'])) {
    $validationResult->addError('username', 'Input required');
}

You can now test the ValidationResult and throw an exception if it contains errors.

<?php
if ($validationResult->fails()) {
    throw new ValidationException('Please check your input', $validationResult);
}

Validating form data

Login example:

<?php

use Selective\Validation\Exception\ValidationException;
use Selective\Validation\ValidationResult;

// ...

// Get all POST values
$data = (array)$request->getParsedBody();

$validation = new ValidationResult();

// Validate username
if (empty($data['username'])) {
    $validation->addError('username', 'Input required');
}

// Validate password
if (empty($data['password'])) {
    $validation->addError('password', 'Input required');
}

// Check validation result
if ($validation->fails()) {
    // Trigger error response (see validation middleware)
    throw new ValidationException('Please check your input', $validation);
}

Validating JSON

Validating a JSON request works like validating form data, because in PHP it's just an array from the request object.

<?php
use Selective\Validation\ValidationResult;

// Fetch json data from request as array
$jsonData = (array)$request->getParsedBody();

$validation = new ValidationResult();

// ...

if ($validation->fails()) {
    throw new ValidationException('Please check your input', $validation);
}

In vanilla PHP you can fetch the JSON request as follows:

<?php

$jsonData = (array)json_decode(file_get_contents('php://input'), true);

// ...

Regex

The Selective\Validation\Regex\ValidationRegex class allows you to validate if a given string conforms a defined regular expression.

Example usage:

use Selective\Validation\Factory\CakeValidationFactory;
use Selective\Validation\Regex\ValidationRegex;
// ...

$data = [ /* ... */ ];

$validationFactory = new CakeValidationFactory();
$validator = $validationFactory->createValidator();

$validator
    ->regex('id', ValidationRegex::ID, 'Invalid')
    ->regex('country', ValidationRegex::COUNTRY_ISO_2, 'Invalid country')
    ->regex('date_of_birth', ValidationRegex::DATE_DMY, 'Invalid date format');

Middleware

The ValidationExceptionMiddleware catches the ValidationException and converts it into a nice JSON response.

Slim 4 integration

Insert a container definition for ValidationExceptionMiddleware::class:

<?php

use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Selective\Validation\Encoder\JsonEncoder;
use Selective\Validation\Middleware\ValidationExceptionMiddleware;
use Selective\Validation\Transformer\ErrorDetailsResultTransformer;
use Slim\App;
use Slim\Factory\AppFactory;
// ...

return [
    ValidationExceptionMiddleware::class => function (ContainerInterface $container) {
        $factory = $container->get(ResponseFactoryInterface::class);

        return new ValidationExceptionMiddleware(
            $factory, 
            new ErrorDetailsResultTransformer(), 
            new JsonEncoder()
        );
    },

    ResponseFactoryInterface::class => function (ContainerInterface $container) {
        $app = $container->get(App::class);

        return $app->getResponseFactory();
    },

    App::class => function (ContainerInterface $container) {
        AppFactory::setContainer($container);

        return AppFactory::create();
    },

    // ...

];

Add the ValidationExceptionMiddleware into your middleware stack:

<?php

use Selective\Validation\Middleware\ValidationExceptionMiddleware;
use Slim\Factory\AppFactory;

require_once __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

// ...

$app->add(ValidationExceptionMiddleware::class);

// ...

$app->run();

Usage in Slim

<?php

use Selective\Validation\ValidationException;
use Selective\Validation\ValidationResult;

$validation = new ValidationResult();

// Validate username
if (empty($data->username)) {
    $validation->addError('username', 'Input required');
}

// Check validation result
if ($validation->fails()) {
    // Trigger the validation middleware
    throw new ValidationException('Please check your input', $validation);
}

Validators

You can combine this library with a validator that is doing the actual validation of your input data.

The converter pattern makes it easy to map instances of one class into instances of another class.

CakePHP Validator

The cakephp/validation library provides features to build validators that can validate arbitrary arrays of data with ease.

Installation

composer require cakephp/validation

Usage

The Cake\Validation\Validator::validate() method returns a non-empty array when there are validation failures. The list of errors then can be converted into a ValidationResult using the Selective\Validation\Factory\CakeValidationFactory or Selective\Validation\Converter\CakeValidationConverter.

For example, if you want to validate a login form you could do the following:

use Selective\Validation\Factory\CakeValidationFactory;
use Selective\Validation\Exception\ValidationException;
// ...

// Within the Action class: fetch the request data, e.g. from a JSON request
$data = (array)$request->getParsedBody();

// Within the Application Service class: Do the validation
$validationFactory = new CakeValidationFactory();
$validator = $validationFactory->createValidator();

$validator
    ->notEmptyString('username', 'Input required')
    ->notEmptyString('password', 'Input required');

$validationResult = $validationFactory->createValidationResult(
    $validator->validate($data)
);

if ($validationResult->fails()) {
    throw new ValidationException('Please check your input', $validationResult);
}

Please note: The CakeValidationFactory should be injected via constructor.

Read more: https://odan.github.io/2020/10/18/slim4-cakephp-validation.html

Transformer

If you want to implement a custom response data structure, you can implement a custom transformer against the \Selective\Validation\Transformer\ResultTransformerInterface interface.

Example

<?php

namespace App\Transformer;

use Selective\Validation\Exception\ValidationException;
use Selective\Validation\Transformer\ResultTransformerInterface;
use Selective\Validation\ValidationResult;

final class MyValidationTransformer implements ResultTransformerInterface
{
    public function transform(
        ValidationResult $validationResult, 
        ValidationException $exception = null
    ): array {
        // Implement your own data structure for the response
        // ...

        return [];
    }
}

License

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].