PHPackages                             lusito/insanity - 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. [HTTP &amp; Networking](/categories/http)
4. /
5. lusito/insanity

AbandonedArchivedLibrary[HTTP &amp; Networking](/categories/http)

lusito/insanity
===============

Extensible library for validating and sanitizing various input sources like $\_POST and routing parameters.

1.0.1(6y ago)061[2 issues](https://github.com/Lusito/insanity/issues)[2 PRs](https://github.com/Lusito/insanity/pulls)ZlibPHPPHP ^7.1.0

Since Jun 30Pushed 3y agoCompare

[ Source](https://github.com/Lusito/insanity)[ Packagist](https://packagist.org/packages/lusito/insanity)[ Docs](https://github.com/lusito/insanity)[ RSS](/packages/lusito-insanity/feed)WikiDiscussions develop Synced 3d ago

READMEChangelogDependencies (2)Versions (6)Used By (0)

InSanity
========

[](#insanity)

[![License](https://camo.githubusercontent.com/b714d5b96797f7b932fd8d67b59d4d2aece0901f8eaed44436dd1d126cb99f87/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d7a6c69622f6c6962706e672d626c75652e737667)](https://github.com/Lusito/insanity/blob/master/LICENSE)

Master[![Build Status](https://camo.githubusercontent.com/a27624ac7297ab0952484e681b5f7e5b26cc9b18f02da197d25bc51dda9457ba/68747470733a2f2f7472617669732d63692e6f72672f4c757369746f2f696e73616e6974792e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/Lusito/insanity)[![Code Coverage](https://camo.githubusercontent.com/7be2f3228d0598cfd24286ec4bc75e87cc9efcf2b18db13a9ff0074e2be178be/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f4c757369746f2f696e73616e6974792f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/Lusito/insanity)Develop[![Build Status](https://camo.githubusercontent.com/ef9a61ed7ab8f3a777cbbdc9c9a2c9415440ff75a07a650183395d71c7a31c54/68747470733a2f2f7472617669732d63692e6f72672f4c757369746f2f696e73616e6974792e7376673f6272616e63683d646576656c6f70)](https://travis-ci.org/Lusito/insanity)[![Code Coverage](https://camo.githubusercontent.com/fb687d7d571aab4915b762a23140ba62ca9c260cb65eecf9a67776ca07238cef/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f4c757369746f2f696e73616e6974792f62616467652e7376673f6272616e63683d646576656c6f70)](https://coveralls.io/github/Lusito/insanity)Extensible validation and sanitization library for various input sources like `$_POST` and routing parameters.

### Why InSanity?

[](#why-insanity)

- Supports validation of various input sources (per field configurable)
- Extensible
- Translatable
- Supports global php functions like `trim()`, `intval()`, etc.
- Supports array field inputs
- No dependencies
- Automated tests with 100% code coverage
- Liberal license: [zlib/libpng](https://github.com/Lusito/insanity/blob/master/LICENSE)

**Note**: This has just been released, so it might not be perfect yet. Feel free to report issues, improvement ideas or create pull requests.

### Requirements

[](#requirements)

- PHP &gt;= 7.1

### Installation

[](#installation)

Install via composer:

`composer require lusito/insanity`

Include the autoloader in your php script, unless you've done that already:

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

### Usage

[](#usage)

An example use-case:

```
use Lusito\InSanity\InSanity;

//...

$in = new InSanity(); // or new InSanity($_GET) if you want to use $_GET as default instead of $_POST.
$in->site_id('Site ID', $_GET)->required->is_natural->intval; // use $_GET as input instead of $_POST for this field
$in->parent_id('Parent ID')->required->is_natural->intval;
$in->title('Title')->required->trim->min_length(2)->max_length(255);
$in->slug('Slug')->max_length(255);
$in->visible('Visible')->required->is_bool->boolval;

$errors = $in->getErrors();
if ($errors) {
    http_response_code(400);
    header('Content-Type: application/json');
    echo json_encode(['error' => "Invalid input!", 'validation_errors' => $errors], JSON_UNESCAPED_SLASHES);
} else {
    // Get all values in an associative array:
    $json = $in->toJSON();
}
```

Alternatively, you can grab the values manually like this:

```
use Lusito\InSanity\InSanity;

//...

$in = new InSanity(); // or new InSanity($_GET) if you want to use $_GET as default instead of $_POST.
$siteId = $in->site_id('Site ID', $_GET)->required->is_natural->intval->getValue(); // use $_GET as input instead of $_POST for this field
$parentId = $in->parent_id('Parent ID')->required->is_natural->intval->getValue();
$title = $in->title('Title')->required->trim->min_length(2)->max_length(255)->getValue();
$slug = $in->slug('Slug')->max_length(255)->getValue();
$visible = $in->visible('Visible')->required->is_bool->boolval->getValue();

//...
```

### The classes

[](#the-classes)

This library consists of these classes:

- `InSanity`: This coordinates the validation process.
- `Field`: Used to chain rules and sanitizers to process values. Instances are automatically created.
- `RuleHandler`: A class that contains the included rules.
- `ErrorHandler`: Aggregates errors.
- `Translator`: A class used to translate messages and field names.

The last 3 classes can be extended or even replaced with your own implementations if you feel like it.

Details follow:

#### InSanity

[](#insanity-1)

This class receives 3 parameters:

- An optional (associative) array that serves as the default input if none was specified. If this is `null`, `$_POST` will be used.
- An optional instance of `RuleHandler` (or a replacement class). If `null`, a default `RuleHandler` is created.
- An optional instance of `ErrorHandler` (or a replacement class). If `null`, a default `ErrorHandler` is created.

To start validation and sanitization on a field, call it like this:

```
$in = new InSanity();
$in->my_field_name('My Field Label')->required->trim->min_length(2);
```

This consists of 2 parts:

- `$in->my_field_name('My Field Label')`
    - `my_field_name` is the field name as it exists in the input array.
    - `My Field Label` is the text that will be used when generating error messages.
    - This returns an instance of `Field`.
- `->required->trim->min_length(2)`
    - These apply your rules. Rule calls return the `Field` instance for easy chaining.

You can get errors using `$in->getErrors()`. If you need to access a field afterwards (or apply an additional later), you can access the fields later by using `$in->my_field_name`.

For convenience, a method `$in->toJSON()` exists, which will create an associative array field\_name =&gt; field\_value.

#### Field

[](#field)

Field instances are created by `InSanity` (see above). The instance supports executing and chaining rules.

A rule can be run in 3 different ways:

```
// shortest way:
$field->required;
// does the same as:
$field->required();
// A parameter can be supplied like this:
$field->min_length(2);
```

The rule (and filter) methods are applied in order. If the given method returns a boolean value, it's interpreted as a rule, otherwise as a filter (the sole exception is `boolval`, see below).

Examples:

- A return value of false will fail the validation (and skip the rest of the rules)
- A value of true will continue with the next rule (or filter).
- Anything else will change the current value to what has been returned by the rule handler.

Some methods exist in addition to normal rule handling:

- `default(default)`: If value is `null`, value will be set to `default`.
- `boolval()`: This was added for two reasons:
    - `boolval` from PHP doesn't work on the same values as the is\_bool rule.
    - it returns true or false, which would normally be interpreted as a validation result and thus, not be stored.
- `getValue()`: Gets the current value of the field (after rules have been applied)
- `getError()`: Gets the error message, or `null` if no error has been set yet.
- `setFailed(rule, param=null)`: Sets the field to failed. An error message will be generated using the translator class.

#### RuleHandler

[](#rulehandler)

As said, RuleHandler contains validation methods. That method receives 1-2 parameters. The first being the value to validate and the second is the parameter passed by the user (`null` if none given).

The following rules are included in the built-in RuleHandler class:

- `is_alpha` (a-z)
- `is_alnum` (a-z and 0-9)
- `is_alnum_dash` (a-z, 0-9, \_ and -)
- `is_numeric` (a numeric value, prefixed by a + or a -)
- `is_integer` (an integer value, prefixed by a + or a -)
- `is_natural` (an integer value without prefix)
- `is_natural_no_zero` (an integer value without prefix and above zero)
- `is_bool` (true|false|on|off|yes|no|1|0)
- `valid_email` (a valid e-mail address)
- `required` (the trimmed value may not be empty)
- `min_length(length)` (the value must have a minimum length)
- `max_length(length)` (the value must have a maximum length)
- `exact_length(length)` (the value must have a specified length)

#### Translator

[](#translator)

If you plan on writing your own rules or if you need more than english as target language, you can either add/override translations by supplying an associative array to the constructor or you can write your own implementation.

#### ErrorHandler

[](#errorhandler)

The ErrorHandler builds and aggregates error messages. It will create a new `Translator` instance when needed. If you want it to use a custom `Translator` instance, either pass the instance as first argument to the constructor, or override the `getTranslator()` method.

### Report isssues

[](#report-isssues)

Something not working quite as expected? Do you need a feature that has not been implemented yet? Check the [issue tracker](https://github.com/Lusito/insanity/issues) and add a new one if your problem is not already listed. Please try to provide a detailed description of your problem, including the steps to reproduce it.

### Contribute

[](#contribute)

Awesome! If you would like to contribute with a new feature or submit a bugfix, fork this repo and send a pull request. Please, make sure all the unit tests are passing before submitting and add new ones in case you introduced new features.

### License

[](#license)

InSanity has been released under the [zlib/libpng](https://github.com/Lusito/insanity/blob/master/LICENSE) license, meaning you can use it free of charge, without strings attached in commercial and non-commercial projects. Credits are appreciated but not mandatory.

###  Health Score

25

—

LowBetter than 37% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity5

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~225 days

Total

2

Last Release

2285d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/4c9f1143a4a1ff6fbd0051287a9734a082e589ca04c93de85f47103301fe4f04?d=identicon)[Lusito](/maintainers/Lusito)

---

Top Contributors

[![Lusito](https://avatars.githubusercontent.com/u/1135267?v=4)](https://github.com/Lusito "Lusito (17 commits)")

---

Tags

validationrestroutingfieldinputfilteringsanitizationsanitizing

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/lusito-insanity/health.svg)

```
[![Health](https://phpackages.com/badges/lusito-insanity/health.svg)](https://phpackages.com/packages/lusito-insanity)
```

###  Alternatives

[handcraftedinthealps/rest-routing-bundle

This bundle provides automatic route registration for the Controllers

582.0M2](/packages/handcraftedinthealps-rest-routing-bundle)[contributte/api-router

RESTful Router for your Apis in Nette Framework - created either directly or via attributes

20802.8k3](/packages/contributte-api-router)[elementaryframework/water-pipe

URL routing framework and requests/responses handler for PHP

254.6k4](/packages/elementaryframework-water-pipe)

PHPackages © 2026

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