Skip to content

Commit c39ed7b

Browse files
authored
Update README.md
1 parent db55348 commit c39ed7b

1 file changed

Lines changed: 64 additions & 0 deletions

File tree

README.md

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# Validation
22

3+
A validation library for PHP that uses the [notification pattern](https://martinfowler.com/articles/replaceThrowWithNotification.html).
4+
35
[![Latest Version on Packagist](https://img.shields.io/github/release/selective-php/validation.svg)](https://packagist.org/packages/selective/validation)
46
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](LICENSE)
57
[![Build Status](https://github.com/selective-php/validation/workflows/build/badge.svg)](https://github.com/selective-php/validation/actions)
@@ -19,6 +21,38 @@ composer require selective/validation
1921

2022
## Usage
2123

24+
> A Notification collects together errors
25+
26+
In order to use a notification, you have to create the `ValidationResult` object.
27+
A `ValidationResult` can be really simple, sometimes just a list of strings will do the trick.
28+
29+
```php
30+
<?php
31+
32+
use Selective\Validation\ValidationException;
33+
use Selective\Validation\ValidationResult;
34+
35+
$validationResult = new ValidationResult();
36+
37+
if (empty($data['username'])) {
38+
$validationResult->addError('username', 'Input required');
39+
}
40+
```
41+
42+
You can now test the `ValidationResult` and throw an exception if it contains errors.
43+
44+
```php
45+
if ($validationResult->isFailed()) {
46+
// Global error message
47+
$validationResult->setMessage('Please check your input');
48+
49+
// Trigger error response (see validation middleware)
50+
throw new ValidationException($validationResult);
51+
}
52+
```
53+
54+
## Validating form data
55+
2256
Login example:
2357

2458
```php
@@ -54,6 +88,36 @@ if ($validation->isFailed()) {
5488
}
5589
```
5690

91+
### Validating JSON
92+
93+
Validating a JSON request works like validating form data, because in PHP it's just an array from the request object.
94+
95+
```php
96+
<?php
97+
98+
// Fetch json data from request as array
99+
$jsonData = (array)$request->getParsedBody();
100+
101+
$validation = new ValidationResult();
102+
103+
// ...
104+
105+
if ($validation->isFailed()) {
106+
$validation->setMessage('Please check your input');
107+
throw new ValidationException($validation);
108+
}
109+
```
110+
111+
In vanilla PHP you can fetch the JSON request as follows:
112+
113+
```php
114+
<?php
115+
116+
$jsonData = (array)json_decode(file_get_contents('php://input'), true);
117+
118+
// ...
119+
```
120+
57121
### Middleware
58122

59123
The `ValidationExceptionMiddleware` PSR-15 middleware catches all exceptions and converts

0 commit comments

Comments
 (0)