PHPackages                             gin0115/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. [Validation &amp; Sanitization](/categories/validation)
4. /
5. gin0115/slim-validation

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

gin0115/slim-validation
=======================

A validator for the Slim PHP Micro-Framework

4.0.0-rc1(3y ago)025[1 PRs](https://github.com/gin0115/SlimValidation/pulls)1MITPHPPHP &gt;=7.1

Since Oct 19Pushed 3y agoCompare

[ Source](https://github.com/gin0115/SlimValidation)[ Packagist](https://packagist.org/packages/gin0115/slim-validation)[ Docs](https://github.com/awurth/SlimValidation)[ RSS](/packages/gin0115-slim-validation/feed)WikiDiscussions master Synced today

READMEChangelog (1)Dependencies (5)Versions (5)Used By (1)

Slim Validation
===============

[](#slim-validation)

[![SensioLabsInsight](https://camo.githubusercontent.com/6fed90c11075219a6810f0b2290467ddd0a81509eff39b3ec1867338c5925d7b/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f62646635323735332d663337392d343163362d383563662d6431643133373962346161372f6d696e692e706e67)](https://insight.sensiolabs.com/projects/bdf52753-f379-41c6-85cf-d1d1379b4aa7)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/7fe8ed164ed225d1e51fe697066d4dd2a8b4387f694c3fdb88e14784ae77ab24/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6177757274682f736c696d2d76616c69646174696f6e2f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/awurth/slim-validation/?branch=master)[![Build Status](https://camo.githubusercontent.com/f2aaf1a7fb390db656ef7fcd4df899759f51b6dd7e8720d755adb8e296daafdd/68747470733a2f2f7472617669732d63692e6f72672f6177757274682f536c696d56616c69646174696f6e2e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/awurth/SlimValidation)[![Latest Stable Version](https://camo.githubusercontent.com/7673a38f6fcff9b3355bb7fe98919d7fc3d6ddde9cdb76f930d90508cd332f9c/68747470733a2f2f706f7365722e707567782e6f72672f6177757274682f736c696d2d76616c69646174696f6e2f762f737461626c65)](https://packagist.org/packages/awurth/slim-validation)[![Total Downloads](https://camo.githubusercontent.com/48b8ef6e169f345bd7bb8bf09e81c85864754ab4130844e14cd96e78f5c60fcc/68747470733a2f2f706f7365722e707567782e6f72672f6177757274682f736c696d2d76616c69646174696f6e2f646f776e6c6f616473)](https://packagist.org/packages/awurth/slim-validation)[![License](https://camo.githubusercontent.com/4958f1470bed7a83c015f8bba02700d85c114d68e16519c52a112fe781f67e94/68747470733a2f2f706f7365722e707567782e6f72672f6177757274682f736c696d2d76616c69646174696f6e2f6c6963656e7365)](https://packagist.org/packages/awurth/slim-validation)

A validator for PHP, using [Respect Validation](https://github.com/Respect/Validation) (**Requires PHP 7+**)

> This project was originally designed to be used with the Micro-Framework "Slim", but can now be used with any [psr/http-message](https://github.com/php-fig/http-message)compliant framework, or any other PHP project if you don't need request parameters validation.

Installation
------------

[](#installation)

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

### Configuration

[](#configuration)

To initialize the validator, create a new instance of `Awurth\SlimValidation\Validator`

```
Validator::__construct([ bool $showValidationRules = true [, array $defaultMessages = [] ]])
```

##### $showValidationRules

[](#showvalidationrules)

- If set to `true`, errors will be stored in an associative array with the validation rules names as the key

```
$errors = [
    'username' => [
        'length' => 'The username must have a length between 8 and 16',
        'alnum' => 'The username must contain only letters (a-z) and digits (0-9)'
    ]
];
```

- If set to `false`, errors will be stored in an array of strings

```
$errors = [
    'username' => [
        'The username must have a length between 8 and 16',
        'The username must contain only letters (a-z) and digits (0-9)'
    ]
];
```

##### $defaultMessages

[](#defaultmessages)

An array of messages to overwrite the default [Respect Validation](https://github.com/Respect/Validation) messages

```
$defaultMessages = [
    'length' => 'This field must have a length between {{minValue}} and {{maxValue}} characters',
    'notBlank' => 'This field is required'
];
```

### Add the validator as a service

[](#add-the-validator-as-a-service)

You can add the validator to the app container to access it easily through your application

```
$container['validator'] = function () {
    return new Awurth\SlimValidation\Validator();
};
```

Usage
-----

[](#usage)

```
use Respect\Validation\Validator as V;

// The validate method returns the validator instance
$validator = $container->validator->validate($request, [
    'get_or_post_parameter_name' => V::length(6, 25)->alnum('_')->noWhitespace(),
    // ...
]);

if ($validator->isValid()) {
    // Do something...
} else {
    $errors = $validator->getErrors();
}
```

### Validation methods

[](#validation-methods)

#### Request parameters validation

[](#request-parameters-validation)

```
$_POST = [
    'username' => 'awurth',
    'password' => 'my_password'
];
```

```
/**
 * @var Psr\Http\Message\ServerRequestInterface $request
 */

$validator->request($request, [
    'username' => V::notBlank(),
    'password' => V::length(8)
]);
```

#### Object properties validation

[](#object-properties-validation)

```
class ObjectToValidate {
    private $privateProperty;
    protected $protectedProperty;
    public $pulicProperty;

    // ...
}
```

```
/**
 * @var object $object
 */

$validator->object($object, [
    'privateProperty' => V::notBlank(),
    'protectedProperty' => V::notBlank(),
    'publicProperty' => V::notBlank()
]);
```

If a property does not exist, the tested value will be `null`

#### Array validation

[](#array-validation)

```
$arrayToValidate = [
    'key_1' => 'value_1',
    'key_2' => 'value_2'
];
```

```
/**
 * @var array $arrayToValidate
 */

$validator->array($arrayToValidate, [
    'key_1' => V::notBlank(),
    'key_2' => V::notBlank()
]);
```

#### Single value validation

[](#single-value-validation)

```
$validator->value('12345', V::numeric(), 'secret_code');
```

#### The validate() method

[](#the-validate-method)

```
/**
 * @var Psr\Http\Message\ServerRequestInterface $request
 */

$validator->validate($request, [
    'param' => V::notBlank()
]);

/**
 * @var object $object
 */

$validator->validate($object, [
    'property' => V::notBlank()
]);

/**
 * @var array $array
 */

$validator->array($array, [
    'key' => V::notBlank()
]);

$secretCode = '12345';
$validator->validate($secretCode, [
    'rules' => V::numeric(),
    'key' => 'secret_code'
]);
```

### Error groups

[](#error-groups)

```
$user = [
    'username' => 'awurth',
    'password' => 'my_password'
];

$address = [
    'street' => '...',
    'city' => '...',
    'country' => '...'
];

$validator->validate($user, [
    // ...
], 'user');

$validator->validate($address, [
    // ...
], 'address');
```

```
$validator->getErrors();

// Will return:
[
    'user' => [
        'username' => [
            // Errors...
        ]
    ],
    'address' => [
        'street' => [
            // Errors...
        ]
    ]
]
```

### Custom messages

[](#custom-messages)

Slim Validation allows you to set custom messages for validation errors. There are 4 types of custom messages

#### Default rules messages

[](#default-rules-messages)

The ones defined in the `Validator` constructor.

#### Global rules messages

[](#global-rules-messages)

Messages that overwrite **Respect Validation** and **default rules messages** when calling the `validate` method.

```
$container->validator->validate($request, [
    'get_or_post_parameter_name' => V::length(6, 25)->alnum('_')->noWhitespace(),
    // ...
], null, [
    'length' => 'Custom message',
    'alnum' => 'Custom message',
    // ...
]);
```

#### Individual rules messages

[](#individual-rules-messages)

Messages for a single request parameter. Overwrites all above messages.

```
$container->validator->validate($request, [
    'get_or_post_parameter_name' => [
        'rules' => V::length(6, 25)->alnum('_')->noWhitespace(),
        'messages' => [
            'length' => 'Custom message',
            'alnum' => 'Custom message',
            // ...
        ]
    ],
    // ...
]);
```

#### Single parameter messages

[](#single-parameter-messages)

Defines a single error message for a request parameter, ignoring the validation rules. Overwrites all messages.

```
$container->validator->validate($request, [
    'get_or_post_parameter_name' => [
        'rules' => V::length(6, 25)->alnum('_')->noWhitespace(),
        'message' => 'This field must have a length between 6 and 25 characters and contain only letters and digits'
    ],
    // ...
]);
```

Twig extension
--------------

[](#twig-extension)

This package comes with a Twig extension to display error messages and submitted values in your Twig templates. You can skip this step if you don't want to use it.

To use the extension, you must install twig first

```
$ composer require slim/twig-view
```

### Configuration

[](#configuration-1)

```
$container['view'] = function ($container) {
    // Twig configuration
    $view = new Slim\Views\Twig(...);
    // ...

    // Add the validator extension
    $view->addExtension(
        new Awurth\SlimValidation\ValidatorExtension($container['validator'])
    );

    return $view;
};
```

### Functions

[](#functions)

```
{# Use has_errors() function to know if a form contains errors #}
{{ has_errors() }}

{# Use has_error() function to know if a request parameter is invalid #}
{{ has_error('param') }}

{# Use error() function to get the first error of a parameter #}
{{ error('param') }}

{# Use errors() function to get all errors #}
{{ errors() }}

{# Use errors() function with the name of a parameter to get all errors of a parameter #}
{{ errors('param') }}

{# Use val() function to get the value of a parameter #}
{{ val('param') }}
```

Example
-------

[](#example)

##### AuthController.php

[](#authcontrollerphp)

```
public function register(Request $request, Response $response)
{
    if ($request->isPost()) {
        $this->validator->validate($request, [
            'username' => V::length(6, 25)->alnum('_')->noWhitespace(),
            'email' => V::notBlank()->email(),
            'password' => [
                'rules' => v::length(6, 25),
                'messages' => [
                    'length' => 'This field must have a length between {{minValue}} and {{maxValue}} characters'
                ]
            ],
            'confirm_password' => [
                'rules' => v::equals($request->getParam('password')),
                'messages' => [
                    'equals' => 'The password confirmation must be equal to the password'
                ]
            ]
        ]);

        if ($this->validator->isValid()) {
            // Register user in database

            return $response->withRedirect('url');
        }
    }

    return $this->view->render($response, 'register.twig');
}
```

##### register.twig

[](#registertwig)

```

    {% if has_error('username') %}{{ error('username') }}{% endif %}

    {% if has_error('email') %}{{ error('email') }}{% endif %}

    {% if has_error('password') %}{{ error('password') }}{% endif %}

    {% if has_error('confirm_password') %}{{ error('confirm_password') }}{% endif %}

```

###  Health Score

18

—

LowBetter than 8% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity31

Early-stage or recently created project

 Bus Factor1

Top contributor holds 95.7% 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

Unknown

Total

1

Last Release

1353d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/d82b9e8ef7816d3d0b9812ad233f61f6a313f529e0ac85721781b46ad292e1ea?d=identicon)[glynnquelch](/maintainers/glynnquelch)

---

Top Contributors

[![awurth](https://avatars.githubusercontent.com/u/10026857?v=4)](https://github.com/awurth "awurth (132 commits)")[![khrizt](https://avatars.githubusercontent.com/u/725227?v=4)](https://github.com/khrizt "khrizt (2 commits)")[![Alph44rchitect](https://avatars.githubusercontent.com/u/9463303?v=4)](https://github.com/Alph44rchitect "Alph44rchitect (1 commits)")[![DeeFuse](https://avatars.githubusercontent.com/u/7376678?v=4)](https://github.com/DeeFuse "DeeFuse (1 commits)")[![gin0115](https://avatars.githubusercontent.com/u/28779094?v=4)](https://github.com/gin0115 "gin0115 (1 commits)")[![Gomes81](https://avatars.githubusercontent.com/u/1794381?v=4)](https://github.com/Gomes81 "Gomes81 (1 commits)")

---

Tags

validatorvalidationrespectslim

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[respect/validation

The most awesome validation engine ever created for PHP

6.0k39.9M414](/packages/respect-validation)[awurth/slim-validation

A wrapper around the respect/validation PHP validation library for easier error handling and display

65399.7k9](/packages/awurth-slim-validation)[laminas/laminas-validator

Validation classes for a wide range of domains, and the ability to chain validators to create complex validation criteria

15848.2M222](/packages/laminas-laminas-validator)[telnyx/telnyx-php

Official Telnyx PHP SDK — APIs for Voice, SMS, MMS, WhatsApp, Fax, SIP Trunking, Wireless IoT, Call Control, and more. Build global communications on Telnyx's private carrier-grade network.

35789.4k2](/packages/telnyx-telnyx-php)[davidepastore/slim-validation

A slim middleware for validation based on Respect/Validation

173229.0k3](/packages/davidepastore-slim-validation)[workerman/validation

The most awesome validation engine ever created for PHP. Respect/Validation 汉化版本

2336.5k9](/packages/workerman-validation)

PHPackages © 2026

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