Slim 3 validation implementation (davidepastore/slim-validation)

Hello,

I installed slim 3 with davidepastore/slim-validation for variables validation.

$ composer require davidepastore/slim-validation

I followed below URl and successful able to call api, but it is not validating any variables. Not getting what i am missing or any understanding gap.

https://github.com/DavidePastore/Slim-Validation.

URL: http://192.168.0.205:8081/index8.php/bar
post body : {“username”:“amit45”,“age”:"-4578AAA"}

outcome : {“username”:“amit45”,“age”:"-4578AAA"}amit45-4578AAAmain

expecting : age is in negative so it should give error but not giving.

--------------------------------code-----------------------------------------------------

<?php require '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->add($container->get('validation')); $app->post('/bar', function ($req, $res, $args) { $body = json_decode($req->getBody()); print htmlspecialchars($req->getBody()); $username=$body->username; $age=$body->age; echo "$username"; echo "$age"; #$number =123 ; #v::numeric()->validate($number); // true $usernameValidator = v::alnum()->noWhitespace()->length(1, 5); $usernameValidator->validate('$username'); //Here you expect 'username' and 'age' parameters if($this->validation->hasErrors()){ //There are errors, read them $errors = $this->validation->getErrors(); echo "main"; } else { echo "error"; } }); $app->run(); Regards Anupam

Hello Anupam,

If you are expecting the string error in the output if an error occurs, you need to change the following section:

  if($this->validation->hasErrors()){
    //There are errors, read them
    $errors = $this->validation->getErrors();
    echo "main";

  } else {
    echo "error";
  }

The lines echo "main"; and echo "error"; should be switched.

Dear llvdl,

I removed both echo lines from code, and new outcome is.

{“username”:“amit45”,“age”:"-4578AAA"}

Validation still not. I tried all given method in below URL but not getting where and what i am missing.
https://github.com/DavidePastore/Slim-Validation.

Regards
Anupam

Hello IIvdl,

Will appreciate, if help me on this as you did several times before. I am new for Slim but learning on daily basis.

Regards
Anupam

Hello Anupam,

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();

This can be tested with curl for example:

$ curl -X POST --data "{\"username\":\"amit45\", \"age\": 20}" -H "Content-Type: application/json" localhost:8000/bar 
No validation errors. Data: Array
(
    [username] => amit45
    [age] => 20
)
$ 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
        )

)

Hello llvdl,

Working Thanks again.

Regards
Anupam

one typo correction :

$container[‘validation’] = function () {
to
$container['barValidation '] = function () {

1 Like