https://github.com/selective-php/validation
A validation library for PHP that uses the notification pattern
https://github.com/selective-php/validation
middleware php slim4 validation validator
Last synced: about 1 year ago
JSON representation
A validation library for PHP that uses the notification pattern
- Host: GitHub
- URL: https://github.com/selective-php/validation
- Owner: selective-php
- License: mit
- Created: 2018-04-18T11:14:57.000Z (about 8 years ago)
- Default Branch: master
- Last Pushed: 2023-09-09T22:05:41.000Z (over 2 years ago)
- Last Synced: 2025-03-29T12:04:30.948Z (about 1 year ago)
- Topics: middleware, php, slim4, validation, validator
- Language: PHP
- Homepage:
- Size: 111 KB
- Stars: 34
- Watchers: 4
- Forks: 4
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Validation
A validation library for PHP that uses
the [notification pattern](https://martinfowler.com/articles/replaceThrowWithNotification.html).
[](https://packagist.org/packages/selective/validation)
[](LICENSE)
[](https://github.com/selective-php/validation/actions)
[](https://scrutinizer-ci.com/g/selective-php/validation/code-structure)
[](https://scrutinizer-ci.com/g/selective-php/validation/?branch=master)
[](https://packagist.org/packages/selective/validation/stats)
## Table of contents
* [Requirements](#requirements)
* [Installation](#installation)
* [Usage](#usage)
* [Validating form data](#validating-form-data)
* [Validating JSON](#validating-json)
* [Regex](#regex)
* [Validators](#validators)
* [CakePHP Validator](#cakephp-validator)
* [Transformer](#transformer)
* [License](#license)
## Requirements
* PHP 8.1+
## Installation
```shell
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
addError('username', 'Input required');
}
```
You can now test the `ValidationResult` and throw an exception if it contains errors.
```php
fails()) {
throw new ValidationException('Please check your input', $validationResult);
}
```
## Validating form data
Login example:
```php
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
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
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
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
add(ValidationExceptionMiddleware::class);
// ...
$app->run();
```
#### Usage in Slim
```php
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](https://java-design-patterns.com/patterns/converter/) makes it easy to map instances of one
class into instances of another class.
### CakePHP Validator
The [cakephp/validation](https://github.com/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:
```php
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:**
## 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