Skip to content

Commit 5312016

Browse files
authored
Update README.md
1 parent 6c8df40 commit 5312016

File tree

1 file changed

+43
-2
lines changed

1 file changed

+43
-2
lines changed

README.md

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,50 @@
1717
composer require odan/validation
1818
```
1919

20-
## Documentation
20+
## Usage
2121

22-
This package is documented [here](./docs/readme.md).
22+
Login example:
23+
24+
```php
25+
// Get all POST values
26+
$data = $request->getParsedBody();
27+
28+
$validation = new ValidationResult();
29+
30+
// Validate username
31+
if (empty($data['username'])) {
32+
$validation->addError('email', 'Input required');
33+
}
34+
35+
// Validate password
36+
if (empty($data['password'])) {
37+
$validation->addError('password', 'Input required');
38+
}
39+
40+
// Check validation result
41+
if ($validation->isFailed()) {
42+
// Global error message
43+
$validation->setMessage('Please check you input');
44+
45+
// Trigger error response (see validation middleware)
46+
throw new ValidationException($validation);
47+
}
48+
```
49+
50+
### Slim Middleware
51+
52+
This validation middleware catches the `ValidationException` exception and converts it into a nice JSON response:
53+
54+
```php
55+
// Validation middleware
56+
$app->add(function (Request $request, Response $response, $next) {
57+
try{
58+
return $next($request, $response);
59+
} catch (ValidationException $exception) {
60+
return $response->withStatus(422)->withJson(['error' => $exception->getValidation()->toArray()]);
61+
}
62+
});
63+
```
2364

2465
## License
2566

0 commit comments

Comments
 (0)