Skip to content
Validation Result and Exception
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src/Validation
tests
.cs.php
.gitattributes
.gitignore
.scrutinizer.yml
.travis.yml
LICENSE
README.md
_config.yml
build.xml
composer.json
phpstan.neon
phpunit.xml

README.md

Validation

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

Requirements

  • PHP 7.1+

Installation

composer require selective/validation

Usage

Login example:

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

// ...

// Get all POST values
$data = $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->isFailed()) {
    // Global error message
    $validation->setMessage('Please check your input');

    // Trigger error response (see validation middleware)
    throw new ValidationException($validation);
}

PSR-7 Middleware

This validation middleware catches the ValidationException exception and converts it into a nice JSON response:

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Selective\Validation\ValidationException;

// Validation middleware
$app->add(function (Request $request, Response $response, $next) {
    try{
        return $next($request, $response);
    } catch (ValidationException $exception) {
        return $response->withStatus(422)->withJson(['error' => $exception->getValidation()->toArray()]);
    }
});

License

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

You can’t perform that action at this time.