andrewdyer / slim3-validator
A validation library for the Slim Framework built using Respect/Validation
Requires
- php: >=7.0.0
- respect/validation: ^1.1.29
- slim/slim: ^3.11.0
This package is auto-updated.
Last update: 2024-12-22 18:55:21 UTC
README
A validation library for the Slim Framework built using Respect/Validation.
License
Licensed under MIT. Totally free for private or commercial projects.
Installation
composer require andrewdyer/slim3-validator
Usage
use Slim\App; use Anddye\Validation\Validator; use Respect\Validation\Validator as v; $app = new App(); $container = $app->getContainer(); $container['validationService'] = function () { return new Validator(); }; $app->get('/', function (Request $request, Response $response) use ($container) { $validation = $container['validationService']->validate($request, [ 'email' => v::email()->length(1, 254)->notEmpty(), 'forename' => v::alpha()->length(1, 100)->notEmpty()->noWhitespace(), 'password' => v::length(8, 100)->notEmpty(), 'surname' => v::alpha()->length(1, 100)->notEmpty()->noWhitespace(), 'username' => v::alnum()->length(1, 32)->notEmpty()->noWhitespace(), ]); if (!$validation->hasPassed()) { // Validation has not passed } else { // Validation has passed } }); $app->run();
Attach a new instance of Anddye\Validation\Validator;
to your applications container so
it can be accessed anywhere you need.
$container['validationService'] = function () { return new \Anddye\Validation\Validator(); };
You can easily validate your form inputs using the validate() helper. Assign to a
variable the validate()
method - passing in the $request object as well as an array
where the array key represents the name of the field and the array value represents
the validation rules.
$validation = $container['validationService']->validate($request, [ 'email' => v::email()->length(1, 254)->notEmpty(), 'forename' => v::alpha()->length(1, 100)->notEmpty()->noWhitespace(), 'password' => v::length(8, 100)->notEmpty(), 'surname' => v::alpha()->length(1, 100)->notEmpty()->noWhitespace(), 'username' => v::alnum()->length(1, 32)->notEmpty()->noWhitespace(), ]);
Respect\Validation is namespaced, but you can make your life easier by importing a single class into your context:
use Respect\Validation\Validator as v;
You can then check if the validation has passed using the hasPassed()
method:
if (!$validation->hasPassed()) { // Validation has not passed } else { // Validation has passed }
If the validation has failed, an array of the validation errors can be accessed
by calling the getErrors()
method:
foreach ($validation->getErrors() as $input => $errors) { foreach ($errors as $error) { echo $error; } }
Support
If you are having general issues with this library, then please feel free to contact me on Twitter.
If you believe you have found an issue, please report it using the issue tracker, or better yet, fork the repository and submit a pull request.
If you're using this package, I'd love to hear your thoughts!