PHPackages                             werx/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. werx/validation

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

werx/validation
===============

Validate individual data elements or group validation rules into sets to validate a form.

1.3.0(11y ago)86.1k4[1 PRs](https://github.com/werx/validation/pulls)3MITPHPPHP &gt;= 5.4

Since Feb 2Pushed 8y ago1 watchersCompare

[ Source](https://github.com/werx/validation)[ Packagist](https://packagist.org/packages/werx/validation)[ RSS](/packages/werx-validation/feed)WikiDiscussions master Synced 3w ago

READMEChangelogDependencies (2)Versions (12)Used By (3)

Validation Library
==================

[](#validation-library)

Simple input validation.

[![Build Status](https://camo.githubusercontent.com/8b219628de7018232034c43b4cedaacad974c419bb33983c6a6e04875c1b52a6/68747470733a2f2f7472617669732d63692e6f72672f776572782f76616c69646174696f6e2e706e673f6272616e63683d6d6173746572)](https://travis-ci.org/werx/validation) [![Total Downloads](https://camo.githubusercontent.com/5e18eaa5973f2d176ccbe39783dfb153e9dfbfc9d27c8b537322eb58bb25d4d3/68747470733a2f2f706f7365722e707567782e6f72672f776572782f76616c69646174696f6e2f646f776e6c6f6164732e706e67)](https://packagist.org/packages/werx/validation) [![Latest Stable Version](https://camo.githubusercontent.com/665a9afd0a206cf78691f7d440de275a15e9902dde8c708e7b2c633ae1e98401/68747470733a2f2f706f7365722e707567782e6f72672f776572782f76616c69646174696f6e2f762f737461626c652e706e67)](https://packagist.org/packages/werx/validation)

Usage
-----

[](#usage)

There are two components to this library. A set of validation methods and an input validation engine.

### Validators

[](#validators)

The Validator class can be used to quickly validate a single piece of input.

```
include 'vendor/autoload.php';

use werx\Validation\Validator;

$input = 'foo';
$valid = Validator::minlength($input, 4);
var_dump($valid);

/*
bool(true)
*/
```

The following validators are available. Each validator returns a bool. `true` = passed validation, `false` = failed validation.

```
bool required (mixed $input)
bool date (mixed $input [, $input_format = MM/DD/YYYY])
	# Other input formats available YYYY/MM/DD, YYYY-MM-DD, YYYY/DD/MM, YYYY-DD-MM, DD-MM-YYYY, DD/MM/YYYY, MM-DD-YYYY, MM/DD/YYYY, YYYYMMDD, YYYYDDMM
bool minlength(mixed $input, int $min)
bool maxlength(mixed $input, int $max)
bool exactlength(mixed $input, int $length)
bool greaterthan($input, int $min)
bool lessthan(mixed $input, int $max)
bool alpha(mixed $input)
bool alphanumeric(mixed $input)
bool integer(mixed $input)
bool float(mixed $input)
bool numeric(mixed $input)
bool email(mixed $input)
bool url(mixed $input)
bool phone(mixed $input)
bool zipcode(mixed $input)
bool startswith(mixed $input, string $match)
bool endswith(mixed $input, string $match)
bool contains(mixed $input, string $match)
bool regex(mixed $input, string $regex)
bool inlist(mixed $input, array $list)
```

### Validation Engine

[](#validation-engine)

The Validation Engine is used to validate a set of data against a set of rules.

#### Usage

[](#usage-1)

First, get an instance of the Validation Engine:

```
use werx\Validation\Engine as ValidationEngine;

$validator = new ValidationEngine;
```

Then add rules:

```
$validator->addRule('firstname', 'First Name', 'required|minlength[2]|alpha');
```

##### Parameters

[](#parameters)

- Form input name / array key of the element you are validating
- User friendly label for the element
- Pipe-delimited list of rules
    - Each rule corresponds to a method name from the Validator class
    - If the method accepts arguments, the args should be in square brackets after the rule name
        - Example: `minlength[2]`
        - Exception: methods which accept an array as parameter should be in curly brackets after the rule name.
            - Example: `inlist{red,white,blue}`
    - Except for the `required` validator, all validators will return true if the input is empty.
        - In other words, `minlength[2]` will only actually fire if you also add a `required` rule.

Now you can get a validation result.

```
$valid = $validator->validate($_POST);
```

##### Validating Input Arrays

[](#validating-input-arrays)

Sometimes you aren't using a simple string as your input field name. Let's say your HTML input form is something like this:

```

```

To build a rule for in this scenario, separate the array name and key name with a period when adding your rule.

```
$validator->addRule('volunteer.name', 'Name', 'required|minlength[2]|alpha');
$validator->addRule('volunteer.email', 'Email Address', 'required|email');
```

#### Closures

[](#closures)

In addition to predefined validation methods from the `Validator` class, you can also use [closures](http://www.php.net/manual/en/functions.anonymous.php) to create custom validation methods.

```
$closure = function ($data, $id, $label) {
	$message = null;
	$success = $data[$id] == 'Foo';

	if (!$success) {
		$message = sprintf('%s must equal "Foo"', $label);
	}

	return [$success, $message];
};

$validator->addRule('firstname', 'First Name', $closure);

$valid = $validator->validate($_POST);
```

Three values will be passed to your closure:

1. The full data set being validated.
2. The id of the element being validated.
3. The label for the element being validated.

The closure is expected to return an array.

- The first element of the array should be the validation result (`bool`).
- The second element of the array should be an error message to display if validation failed.
    - If validation passed, message may be null.

#### Rulesets

[](#rulesets)

What if you want to save groups of rules instead of adding each rule individually every time you want to validate them? We've got you covered.

Create a new class that extends `werx\Validation\Ruleset` and add your rules in the constructor.

```
namespace your\namespace\Rulesets;

use werx\Validation\Ruleset;

class Contact extends Ruleset
{
	public function __construct()
	{
		$this->addRule('firstname', 'First Name', 'required|minlength[2]');
		$this->addRule('lastname', 'Last Name', 'required');
		$this->addRule('phone', 'Phone Number', 'required|phone');
		$this->addRule('email', 'Email Address', 'required|email');
	}
}
```

Then when you are ready to validate this group of rules:

```
$contact_rules = new your\namespace\Rulesets\Contact;
$validator->addRuleset($contact_rules);
$valid = $validator->validate();
```

#### Utility Methods

[](#utility-methods)

There are a couple utilities to make dealing with validation results easier.

##### getErrorSummary()

[](#geterrorsummary)

Returns a simple array containing a list of validation error messages.

```
if (!$valid) {
	$summary = $validator->getErrorSummary();
}

/*
Array
(
	[0] => First Name must only contain the letters A-Z.
	[1] => First Name must be at least 2 characters long.
	[2] => Last Name is a required field.
)
*/
```

##### getErrorSummaryFormatted()

[](#geterrorsummaryformatted)

Returns the error summary formatted as an html unordered list (``).

##### getErrorFields()

[](#geterrorfields)

Returns list of fields that had an error. Useful if you want to apply some decoration to your form indicating which fields had a validation errors.

```
if (!$valid) {
	$error_fields = $validator->getErrorFields();
}

/*
Array
(
	[0] => firstname
	[1] => lastname
)
*/
```

##### getRequiredFields()

[](#getrequiredfields)

Once you've added your rules, you can get back a list of required fields. This is useful when you want to indicate on your form which fields must be completed.

```
$validator->addRule('firstname', 'First Name', 'required');
$validator->addRule('lastname', 'Last Name', 'required');
$validator->addRule('age', 'Age', 'required|integer');

$required = $validator->getRequiredFields();

/*
Array
(
	[0] => firstname
	[1] => lastname
	[2] => age
)
*/
```

##### addCustomMessage()

[](#addcustommessage)

Allows you to set custom error messages.

When displaying the error messages, `{name}` will be replaced with the name of the field being validated. The rest of the field is parsed with [`sprintf()`](http://php.net/sprintf) so that parameters like `minlength` can be placed in the returned error message.

Examples:

```
$validator->addCustomMessage('required', "You didn't provide a value for {name}!");
$validator->addCustomMessage('minlength', "Oops, {name} must be at least %d characters long.");
```

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

[](#installation)

This package is installable and autoloadable via Composer as [werx/validation](https://packagist.org/packages/werx/validation). If you aren't familiar with the Composer Dependency Manager for PHP, [you should read this first](https://getcomposer.org/doc/00-intro.md).

```
$ composer require werx/validation --prefer-dist
```

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

[](#contributing)

### Unit Testing

[](#unit-testing)

```
$ vendor/bin/phpunit
```

### Coding Standards

[](#coding-standards)

This library uses [PHP\_CodeSniffer](http://www.squizlabs.com/php-codesniffer) to ensure coding standards are followed.

I have adopted the [PHP FIG PSR-2 Coding Standard](http://www.php-fig.org/psr/psr-2/) EXCEPT for the tabs vs spaces for indentation rule. PSR-2 says 4 spaces. I use tabs. No discussion.

To support indenting with tabs, I've defined a custom PSR-2 ruleset that extends the standard [PSR-2 ruleset used by PHP\_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer/blob/master/CodeSniffer/Standards/PSR2/ruleset.xml). You can find this ruleset in the root of this project at PSR2Tabs.xml

Executing the codesniffer command from the root of this project to run the sniffer using these custom rules.

```
$ ./codesniffer
```

###  Health Score

35

—

LowBetter than 77% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity26

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 94.1% 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 ~49 days

Recently: every ~108 days

Total

11

Last Release

4025d ago

Major Versions

0.4.0 → 1.0.02014-04-25

### Community

Maintainers

![](https://www.gravatar.com/avatar/1cda8a02682a999e89bc2443c6c169b1dc9228cc4709d0b5fad642dc2a151141?d=identicon)[joshmoody](/maintainers/joshmoody)

---

Top Contributors

[![joshmoody](https://avatars.githubusercontent.com/u/1504862?v=4)](https://github.com/joshmoody "joshmoody (32 commits)")[![jago86](https://avatars.githubusercontent.com/u/1690276?v=4)](https://github.com/jago86 "jago86 (2 commits)")

---

Tags

validatorvalidationvalidaterulesformruleset

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

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

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

###  Alternatives

[proengsoft/laravel-jsvalidation

Validate forms transparently with Javascript reusing your Laravel Validation Rules, Messages, and FormRequest

1.1k2.3M50](/packages/proengsoft-laravel-jsvalidation)[wixel/gump

A fast, extensible &amp; stand-alone PHP input validation class that allows you to validate any data.

1.2k1.4M31](/packages/wixel-gump)[sadegh19b/laravel-persian-validation

A comprehensive Laravel validation package for Persian text, numbers, dates, and Iranian national identifiers

18596.0k1](/packages/sadegh19b-laravel-persian-validation)[awurth/slim-validation

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

65393.6k9](/packages/awurth-slim-validation)[romeoz/rock-validate

Flexible validator for PHP with I18N.

251.7k6](/packages/romeoz-rock-validate)

PHPackages © 2026

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