To have the validation middleware work for JSON request, make sure the content type header is set for the request to application/json. Otherwise the values are not properly read and the validation will fail.
The following should work (I modified the /bar action a bit):
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Respect\Validation\Validator as v;
$app = new \Slim\App();
// Fetch DI Container
$container = $app->getContainer();
// Register provider
$container['validation'] = function () {
//Create the validators
$usernameValidator = v::alnum()->noWhitespace()->length(1, 10);
$ageValidator = v::numeric()->positive()->between(1, 20);
$validators = array(
'username' => $usernameValidator,
'age' => $ageValidator
);
return new \DavidePastore\Slim\Validation\Validation($validators);
};
$app->post('/bar', function ($req, $res, $args) {
if ($this->barValidation->hasErrors()) { // check for errors with hasErrors
$res->write('There are validation errors in the response.');
$res->write(print_r($this->barValidation->getErrors(), 1)); // getErrors contains the error messages per field
} else {
$res->write('No validation errors. Data: ');
$res->write(print_r($req->getParams(), 1)); // data is stored in $req->getParams
}
})->add($container->get('barValidation'));
$app->run();
$ curl -X POST --data "{\"username\":\"amit45\", \"age\": \"-4578AAA\"}" -H "Content-Type: application/json" localhost:8000/bar
There are validation errors in the response.Array
(
[age] => Array
(
[0] => "-4578AAA" must be numeric
[1] => "-4578AAA" must be positive
[2] => "-4578AAA" must be greater than or equal to 1
)
)
Note the use of -H "Content-Type: application/json" in the curl request. This option sets the content type header for the request. The validation will fail without it, as the data will not be parsed as JSON:
$ curl -X POST --data "{\"username\":\"amit45\", \"age\": \"-4578AAA\"}" localhost:8000/bar There are validation errors in the response.Array
(
[username] => Array
(
[0] => null must contain only letters (a-z) and digits (0-9)
[1] => null must have a length between 1 and 10
)
[age] => Array
(
[0] => null must be numeric
[1] => null must be positive
[2] => null must be greater than or equal to 1
)
)