PHPackages                             davidepastore/slim-validation - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. davidepastore/slim-validation

ActiveLibrary[Framework](/categories/framework)

davidepastore/slim-validation
=============================

A slim middleware for validation based on Respect/Validation

v4.0.0(3y ago)171223.7k—8%31[8 issues](https://github.com/DavidePastore/Slim-Validation/issues)[3 PRs](https://github.com/DavidePastore/Slim-Validation/pulls)3GPL-2.0+PHPPHP ^7.2CI failing

Since Jan 2Pushed 2y ago6 watchersCompare

[ Source](https://github.com/DavidePastore/Slim-Validation)[ Packagist](https://packagist.org/packages/davidepastore/slim-validation)[ RSS](/packages/davidepastore-slim-validation/feed)WikiDiscussions 4.0 Synced 1mo ago

READMEChangelog (10)Dependencies (7)Versions (20)Used By (3)

Slim Framework Validation
=========================

[](#slim-framework-validation)

[![Latest version](https://camo.githubusercontent.com/50cae7856a4c23ba37b1f3a264c35fbaa8a1f4ff959ccb202fb16d11fedfb0fa/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f446176696465506173746f72652f536c696d2d56616c69646174696f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/davidepastore/slim-validation)[![Build Status](https://github.com/DavidePastore/Slim-Validation/workflows/Continuous%20Integration/badge.svg?branch=4.0)](https://github.com/DavidePastore/Slim-Validation/actions?query=workflow%3A%22Continuous+Integration%22+branch%3A4.0)[![Coverage Status](https://camo.githubusercontent.com/9206e27153e2bc17688ed9db2c49595c054c4c1676ab1724a6e5ac650744d012/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f636f7665726167652f672f446176696465506173746f72652f536c696d2d56616c69646174696f6e2e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/DavidePastore/Slim-Validation/code-structure)[![Quality Score](https://camo.githubusercontent.com/e8c94fd19b86a6297dd074b989597f8385dbd5a2c38f2ea4c515d2a281a24258/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f646176696465706173746f72652f536c696d2d56616c69646174696f6e2e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/DavidePastore/Slim-Validation)[![Total Downloads](https://camo.githubusercontent.com/107eb09777612ae4b3b58eb14081bbc9385687bbe2df70d6e5b838a4d6e07835/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f646176696465706173746f72652f736c696d2d76616c69646174696f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/davidepastore/slim-validation)[![PSR2 Conformance](https://camo.githubusercontent.com/17bfbc5db518f02e5c4693a47f2cfc2a28273866910a83ee16dc628bbdccfd0a/68747470733a2f2f7374796c6563692e696f2f7265706f732f34383931343035342f736869656c64)](https://styleci.io/repos/48914054/)

A validation library for the Slim Framework. It internally uses [Respect/Validation](https://github.com/Respect/Validation).

Table of contents
-----------------

[](#table-of-contents)

- [Install](#install)
- [Usage](#usage)
    - [Register per route](#register-per-route)
    - [Register for all routes](#register-for-all-routes)
    - [Route parameters](#route-parameters)
    - [JSON requests](#json-requests)
    - [XML requests](#xml-requests)
    - [Translate errors](#translate-errors)
- [Testing](#testing)
- [Contributing](#contributing)
- [Credits](#credits)

Install
-------

[](#install)

Via Composer

```
$ composer require davidepastore/slim-validation
```

Requires Slim 4.0.0 or newer.

Usage
-----

[](#usage)

In most cases you want to register `DavidePastore\Slim\Validation` for a single route, however, as it is middleware, you can also register it for all routes.

### Register per route

[](#register-per-route)

```
use Respect\Validation\Validator as v;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

//Create the validators
$usernameValidator = v::alnum()->noWhitespace()->length(1, 10);
$ageValidator = v::numeric()->positive()->between(1, 20);
$validators = array(
  'username' => $usernameValidator,
  'age' => $ageValidator
);

$app->get('/api/myEndPoint',function ($req, $res, $args) {
    //Here you expect 'username' and 'age' parameters
    if($req->getAttribute('has_errors')){
      //There are errors, read them
      $errors = $req->getAttribute('errors');

      /* $errors contains:
      array(
        'username' => array(
          '"davidepastore" must have a length between 1 and 10',
        ),
        'age' => array(
          '"89" must be lower than or equals 20',
        ),
      );
      */
    } else {
      //No errors
    }

})->add(new \DavidePastore\Slim\Validation\Validation($validators));

$app->run();
```

### Register for all routes

[](#register-for-all-routes)

```
use Respect\Validation\Validator as v;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

//Create the validators
$usernameValidator = v::alnum()->noWhitespace()->length(1, 10);
$ageValidator = v::numeric()->positive()->between(1, 20);
$validators = array(
  'username' => $usernameValidator,
  'age' => $ageValidator
);

// Register middleware for all routes
// If you are implementing per-route checks you must not add this
$app->add(new \DavidePastore\Slim\Validation\Validation($validators));

$app->get('/foo', function ($req, $res, $args) {
  //Here you expect 'username' and 'age' parameters
  if($req->getAttribute('has_errors')){
    //There are errors, read them
    $errors = $req->getAttribute('errors');

    /* $errors contains:
    array(
      'username' => array(
        '"davidepastore" must have a length between 1 and 10',
      ),
      'age' => array(
        '"89" must be lower than or equals 20',
      ),
    );
    */
  } else {
    //No errors
  }
});

$app->post('/bar', function ($req, $res, $args) {
  //Here you expect 'username' and 'age' parameters
  if($req->getAttribute('has_errors')){
    //There are errors, read them
    $errors = $req->getAttribute('errors');
  } else {
    //No errors
  }
});

$app->run();
```

### Route parameters

[](#route-parameters)

```
use Respect\Validation\Validator as v;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

//Create the validators
$routeParamValidator = v::numeric()->positive();
$validators = array(
  'param' => $routeParamValidator,
);

$app->get('/foo/{param}', function ($req, $res, $args) {
  //Here you expect 'param' route parameter
  if($req->getAttribute('has_errors')){
    //There are errors, read them
    $errors = $req->getAttribute('errors');

    /* $errors contains:
    array(
        'param' => array(
          '"wrong" must be numeric',
        ),
    );
    */
  } else {
    //No errors
  }
})->add(new \DavidePastore\Slim\Validation\Validation($validators));

$app->run();
```

Note that requests parameters take priority over route parameters, so if you use the same name for a route and request parameter, the last will win and it will be considered for validation.

### JSON requests

[](#json-requests)

You can also validate a JSON request. Let's say your body request is:

```
{
	"type": "emails",
	"objectid": "1",
	"email": {
		"id": 1,
		"enable_mapping": "1",
		"name": "rq3r",
		"created_at": "2016-08-23 13:36:29",
		"updated_at": "2016-08-23 14:36:47"
	}
}
```

and you want to validate the `email.name` key. You can do it in this way:

```
use Respect\Validation\Validator as v;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

//Create the validators
$typeValidator = v::alnum()->noWhitespace()->length(3, 5);
$emailNameValidator = v::alnum()->noWhitespace()->length(1, 2);
$validators = array(
  'type' => $typeValidator,
  'email' => array(
    'name' => $emailNameValidator,
  ),
);
```

If you'll have an error, the result would be:

```
//In your route
$errors = $req->getAttribute('errors');

print_r($errors);
/*
Array
(
    [email.name] => Array
        (
            [0] => "rq3r" must have a length between 1 and 2
        )

)
*/
```

### XML requests

[](#xml-requests)

You can also validate a XML request. Let's say your body request is:

Let's say you have a POST request with a XML in its body:

```

   emails
   1

     1
     1
     rq3r
     2016-08-23 13:36:29
     2016-08-23 14:36:47

```

and you want to validate the `email.name` key. You can do it in this way:

```
use Respect\Validation\Validator as v;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

//Create the validators
$typeValidator = v::alnum()->noWhitespace()->length(3, 5);
$emailNameValidator = v::alnum()->noWhitespace()->length(1, 2);
$validators = array(
  'type' => $typeValidator,
  'email' => array(
    'name' => $emailNameValidator,
  ),
);
```

If you'll have an error, the result would be:

```
//In your route
$errors = $req->getAttribute('errors');

print_r($errors);
/*
Array
(
    [email.name] => Array
        (
            [0] => "rq3r" must have a length between 1 and 2
        )

)
*/
```

### Translate errors

[](#translate-errors)

You can provide a callable function to translate the errors.

```
use Respect\Validation\Validator as v;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

//Create the validators
$usernameValidator = v::alnum()->noWhitespace()->length(1, 10);
$ageValidator = v::numeric()->positive()->between(1, 20);
$validators = array(
  'username' => $usernameValidator,
  'age' => $ageValidator
);

$translator = function($message){
  $messages = [
      'These rules must pass for {{name}}' => 'Queste regole devono passare per {{name}}',
      '{{name}} must be a string' => '{{name}} deve essere una stringa',
      '{{name}} must have a length between {{minValue}} and {{maxValue}}' => '{{name}} deve avere una dimensione di caratteri compresa tra {{minValue}} e {{maxValue}}',
  ];
  return $messages[$message];
};

$middleware = new \DavidePastore\Slim\Validation\Validation($validators, $translator);

// Register middleware for all routes or only for one...

$app->run();
```

Testing
-------

[](#testing)

```
$ vendor\bin\phpunit
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Credits
-------

[](#credits)

- [Davide Pastore](https://github.com/davidepastore)

###  Health Score

44

—

FairBetter than 92% of packages

Maintenance19

Infrequent updates — may be unmaintained

Popularity51

Moderate usage in the ecosystem

Community24

Small or concentrated contributor base

Maturity67

Established project with proven stability

 Bus Factor1

Top contributor holds 96.8% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~231 days

Recently: every ~397 days

Total

12

Last Release

1246d ago

Major Versions

v0.5.1 → 3.0.x-dev2022-12-15

v3.0.0 → v4.0.02022-12-19

PHP version history (2 changes)v0.1.0PHP &gt;=5.5.0

v4.0.0PHP ^7.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/11a9e9c18e06a1827a69e0b5e7c4644e1f937f70463ff88b25b76b172be5e769?d=identicon)[DavidePastore](/maintainers/DavidePastore)

---

Top Contributors

[![DavidePastore](https://avatars.githubusercontent.com/u/1949364?v=4)](https://github.com/DavidePastore "DavidePastore (91 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")[![iHmD](https://avatars.githubusercontent.com/u/6934421?v=4)](https://github.com/iHmD "iHmD (1 commits)")[![joy2fun](https://avatars.githubusercontent.com/u/7264066?v=4)](https://github.com/joy2fun "joy2fun (1 commits)")

---

Tags

middlewarephpslim-frameworkvalidationmiddlewareframeworkvalidatorvalidationslim

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/davidepastore-slim-validation/health.svg)

```
[![Health](https://phpackages.com/badges/davidepastore-slim-validation/health.svg)](https://phpackages.com/packages/davidepastore-slim-validation)
```

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.8k18.5M1.6k](/packages/cakephp-cakephp)[slim/csrf

Slim Framework 4 CSRF protection PSR-15 middleware

3512.1M94](/packages/slim-csrf)[slim/http-cache

Slim Framework HTTP cache middleware and service provider

1242.9M27](/packages/slim-http-cache)[bnf/slim3-psr15

PSR-15 middleware support for Slim Framework v3

10177.0k5](/packages/bnf-slim3-psr15)[davidepastore/slim-restrict-route

A Slim middleware to restrict ip addresses that will access to your routes

2220.6k1](/packages/davidepastore-slim-restrict-route)[davidepastore/slim-config

A slim middleware to read configuration from different files based on hassankhan/config

338.9k1](/packages/davidepastore-slim-config)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
