# Slim 3 validation implementation (davidepastore/slim-validation)

**URL:** <https://discourse.slimframework.com/t/slim-3-validation-implementation-davidepastore-slim-validation/784>\
**Category:** Questions\
**Created:** [October 7, 2016, 6:37pm UTC](https://discourse.slimframework.com/t/slim-3-validation-implementation-davidepastore-slim-validation/784 "2016-10-07T18:37:19Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![anupam\_4881](https://avatars.discourse-cdn.com/v4/letter/a/59ef9b/32.png) [@anupam\_4881](https://discourse.slimframework.com/u/anupam_4881)\
**Post date:** [October 7, 2016, 6:37pm UTC](https://discourse.slimframework.com/t/slim-3-validation-implementation-davidepastore-slim-validation/784/1 "2016-10-07T18:37:19Z")

</div>

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](https://github.com/DavidePastore/Slim-Validation).

URL: [http://192.168.0.205:8081/index8.php/bar](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

---

<div class="post-metadata">

**Author:** ![llvdl](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.slimframework.com/llvdl/32/78_2.png) [@llvdl](https://discourse.slimframework.com/u/llvdl)\
**Post date:** [October 8, 2016, 6:45am UTC](https://discourse.slimframework.com/t/slim-3-validation-implementation-davidepastore-slim-validation/784/2 "2016-10-08T06:45:04Z")

</div>

Hello Anupam,

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

```php
  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.

---

<div class="post-metadata">

**Author:** ![anupam\_4881](https://avatars.discourse-cdn.com/v4/letter/a/59ef9b/32.png) [@anupam\_4881](https://discourse.slimframework.com/u/anupam_4881)\
**Post date:** [October 8, 2016, 8:08am UTC](https://discourse.slimframework.com/t/slim-3-validation-implementation-davidepastore-slim-validation/784/3 "2016-10-08T08:08:18Z")

</div>

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](https://github.com/DavidePastore/Slim-Validation).

Regards  
Anupam

---

<div class="post-metadata">

**Author:** ![anupam\_4881](https://avatars.discourse-cdn.com/v4/letter/a/59ef9b/32.png) [@anupam\_4881](https://discourse.slimframework.com/u/anupam_4881)\
**Post date:** [October 10, 2016, 9:45am UTC](https://discourse.slimframework.com/t/slim-3-validation-implementation-davidepastore-slim-validation/784/4 "2016-10-10T09:45:46Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![llvdl](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.slimframework.com/llvdl/32/78_2.png) [@llvdl](https://discourse.slimframework.com/u/llvdl)\
**Post date:** [October 10, 2016, 7:32pm UTC](https://discourse.slimframework.com/t/slim-3-validation-implementation-davidepastore-slim-validation/784/5 "2016-10-10T19:32:36Z")

</div>

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
<?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:

```auto
$ 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
)

```

```auto
$ 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:

```auto
$ 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
        )

)

```

---

<div class="post-metadata">

**Author:** ![anupam\_4881](https://avatars.discourse-cdn.com/v4/letter/a/59ef9b/32.png) [@anupam\_4881](https://discourse.slimframework.com/u/anupam_4881)\
**Post date:** [October 11, 2016, 8:05am UTC](https://discourse.slimframework.com/t/slim-3-validation-implementation-davidepastore-slim-validation/784/6 "2016-10-11T08:05:18Z")

</div>

Hello llvdl,

Working Thanks again.

Regards  
Anupam

one typo correction :

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