PHPackages                             phputil/validator - 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. [Testing &amp; Quality](/categories/testing)
4. /
5. phputil/validator

ActiveLibrary[Testing &amp; Quality](/categories/testing)

phputil/validator
=================

Easy and powerful validator for PHP

2.5.2(9y ago)4488↓33.3%1LGPL-3PHPPHP &gt;=5.2.0

Since Oct 23Pushed 8y ago2 watchersCompare

[ Source](https://github.com/thiagodp/validator)[ Packagist](https://packagist.org/packages/phputil/validator)[ Docs](http://github.com/thiagodp/validator)[ RSS](/packages/phputil-validator/feed)WikiDiscussions master Synced 1mo ago

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

phputil\\validator
==================

[](#phputilvalidator)

Easy and powerful validation library for PHP.

[![Build Status](https://camo.githubusercontent.com/fe5934d6b2002306478a4eee988501703e255c779222e3465c781f78479b5bde/68747470733a2f2f7472617669732d63692e6f72672f74686961676f64702f76616c696461746f722e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/thiagodp/validator)

We use [semantic versioning](http://semver.org/). See [our releases](https://github.com/thiagodp/validator/releases).

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

[](#installation)

```
composer require phputil/validator
```

Dependends only on [phputil/rtti](https://github.com/thiagodp/rtti).

An Example
----------

[](#an-example)

A step-by-step example for demonstrating its use.

```
// Suppose that your application receives an object in a JSON like this:
$json =  array( Rule::LENGTH_RANGE => array( 2, 60 ), Option::LABEL => 'Name' ),
	// likes must be greater or equal to zero
	'likes' => array( Rule::MIN_VAUE => 0 ),
	// for the phone...
	'phone' => array( Rule::WITH => array(
		// number must follow a regex
		'number' => array(
			Rule::REGEX => '/^[0-9]{5}\\-[0-9]{4}$/',
			Option::LABEL => 'Phone Number'
			)
	) ),
	// have a friend limit
	'friends' => array( Rule::MAX_COUNT => 100 )
);
// And define the messages (we also could load it from a JSON file)
$messages = array(
	'en' => array( // "en" means "english" locale. This is the default locale.
		Rule::LENGTH_RANGE => '{label} must have from {min_length} to {max_length} characters.',
		Rule::MIN_VAUE => '{label} must be greater than or equal to {min_value}.',
		Rule::REGEX => '{label} has an invalid format.',
		Rule::MAX_COUNT => '{label} must have up to {max_count} item(s).',
	)
);
$validator->setMessages( $messages );

// Now we will check the object using our rules
$problems = $validator->checkObject( $obj, $rules );
// In this moment, problems will be an empty array because all values passed.
// That is: $problems === array()

// However, lets make our rules harder, just to understand how the validation works
$rules[ 'name' ][ Rule::LENGTH_RANGE ] = array( 2, 5 ); // Max of 5
$rule[ 'friends' ][ Rule::MAX_COUNT ] = 1; // just one friend (the best one :-)

// And check again
$problems = $validator->checkObject( $obj, $rules );
// Now $problems is an array like this:
// array(
//	'name' => array( 'length_range' => 'Name must have from 2 to 5 characters.' ),
//	'friends' => array( 'max_count' => 'friends must have up to 1 item(s)' )
// )
// Which means that we have two fields with problems. The format is:
//  field => hurt rule => message
// For example, the field "name" hurt the "length_range" rule and its message is
// "Name must have from 2 to 5 characters.".
//
// If we need to know whether "name" has a problem, we just check with isset:
if ( isset( $problems[ 'name' ] ) ) {
	echo 'Name has a problem', PHP_EOL;
}
// If we are only interested in the messages, and don't care about the fields,
// we just use the ProblemsTransformer
$messages = ( new ProblemsTransformer() )->justTheMessages( $problems );
var_dump( $messages );
// Will print something like:
// array( 'Name must have from 2 to 5 characters.', 'friends must have up to 1 item(s)' )
//
// That's it for now. Enjoy it!
```

Features
--------

[](#features)

- Validates basic types (see [example 1](https://github.com/thiagodp/validator/tree/master/examples/ex1.php))
- Validates arrays (see [example 2](https://github.com/thiagodp/validator/tree/master/examples/ex3.php))
- Validates dynamic objects (`stdClass`) (see [example 3](https://github.com/thiagodp/validator/tree/master/examples/ex3.php))
- Validates objects (of user-created classes) with private or protected attributes (see [example 3](https://github.com/thiagodp/validator/tree/master/examples/ex3.php))
- Supports localized validation messages (different locales)
- Supports different string formats (UTF, ISO-8859-1, ASCII, etc.)

### Available Rules

[](#available-rules)

- `required`
- `min_length`
- `max_length`
- `length_range`
- `min_value`
- `max_value`
- `value_range`
- `min_count` (for arrays)
- `max_count` (for arrays)
- `count_range` (for arrays)
- `in` (for arrays)
- `not_in` (for arrays)
- `start_with` (accepts a string or an array of strings, compared with "or")
- `not_start_with` (accepts a string or an array of strings, compared with "or")
- `end_with` (accepts a string or an array of strings, compared with "or")
- `not_end_with` (accepts a string or an array of strings, compared with "or")
- `contains` (accepts a string or an array of strings, compared with "or")
- `not_contains` (accepts a string or an array of strings, compared with "or")
- `regex`
- `format`: allows to use a format (see [Available Formats](#available-formats))
- `with`: allows to define rules for sub-arrays or sub-objects.
- **custom**: you can add others easily. See below.

#### Adding a custom rule

[](#adding-a-custom-rule)

```
// Adding a custom rule called "myRule" in which the value should be zero:
$validator->setRule( 'myRule', function( $value ) { return 0 == $value; } );
```

Now checking the custom rule:

```
$value = rand( 0, 5 ); // Value to be checked, a random between 0 and 5 (inclusive)
$rules = array( 'myRule' => true ); // Rules to be checked. In this example, just "myRule".
$problems = $validator->check( $value, $rules ); // check() will return the hurt rules
echo isset( $problems[ 'myRule' ] ) ? 'myRule as hurt' : 'passed';
```

### Available Formats

[](#available-formats)

- `anything`
- `string` (same as `anything`)
- `name`
- `word`
- `alphanumeric`
- `alpha`
- `ascii`
- `numeric`
- `integer`
- `double`
- `float` (same as `double`)
- `monetary`
- `price` (same as `monetary`)
- `tax`
- `date` (equals to `date_dmy`)
- `date_dmy`
- `date_mdy`
- `date_ymd`
- `time`
- `longtime`
- `datetime` (equals to `datetime_dmy`)
- `datetime_dmy`
- `datetime_mdy`
- `datetime_ymd`
- `longdatetime` (equals to `longdatetime_dmy`)
- `longdatetime_dmy`
- `longdatetime_mdy`
- `longdatetime_ymd`
- `email`
- `http`
- `url`
- `ip`
- `ipv4`
- `ipv6`
- **custom**: you can add others easily. See below.

You may specify the separator for date-based formats. Default is "/", for example "31/12/1999".

#### Adding a custom format

[](#adding-a-custom-format)

```
// Adding a format "myFormat" in which the value should start with "https://"
$validator->setFormat( 'myFormat', function( $value ) {
	return mb_strpos( $value, 'https://' ) === 0;
	} );
```

Now checking the format:

```
$value = 'http://non-https-site.com';
$rules = array( Rule::FORMAT => 'myFormat' ); // rules to be checked
$problems = $validator->check( $value, $rules ); // check() returns the hurt rules
echo isset( $problems[ Rule::FORMAT ] ) ? 'myFormat as hurt' : 'passed';
```

### Message Replacements

[](#message-replacements)

- `{min_length}` shows the minimum length;
- `{max_length}` shows the maximum length;
- `{length_range}` shows the minimum and the maximum length (e.g. "5-10");
- `{min_value}` shows the minimum value;
- `{max_value}` shows the maximum value;
- `{value_range}` shows minimum and maximum values (e.g. "5-10");
- `{min_count}` shows the minimum count;
- `{max_count}` shows the maximum count;
- `{count_range}` shows the minimum count and the maximum count (e.g. "5-10");
- `{in}` shows the set of items separated by comma;
- `{not_in}` shows the set of items separated by comma;
- `{start_with}` shows the string or the set of strings separated by comma;
- `{not_start_with}` shows the string or the set of strings separated by comma;
- `{end_with}` shows the string or the set of strings separated by comma;
- `{not_end_with}` shows the string or the set of strings separated by comma;
- `{contains}` shows the string or the set of strings separated by comma;
- `{not_contains}` shows the string or the set of strings separated by comma;
- `{regex}` shows the defined regex;
- `{label}` shows the defined label, if defined. Otherwise, shows the array key or object attribute name;
- `{value}` shows the value.

Notes:

- `{min_value}` and `{max_value}` are available when the `{value_range}` is used;
- `{min_length}` and `{max_length}` are available when the `{length_range}` is used;
- `{min_count}` and `{max_count}` are available when the `{count_range}` is used.

### More

[](#more)

- Supports UTF-8 and other common formats (ISO-8859-1, Windows-1251, ASCII, etc.)
- Error messages and formats can be specified by locale.
- Error messages and formats can be specified at once. This allows you, for example, read them from a JSON file.
- Formats and rules can be specified without having to extend any class.
- Classes use a [fluent interface](https://en.wikipedia.org/wiki/Fluent_interface) (that is, you type less).
- Builder classes available (soon)

Tests
-----

[](#tests)

[See here](https://github.com/thiagodp/validator/tree/master/tests).

Examples
--------

[](#examples)

[See all](https://github.com/thiagodp/validator/tree/master/examples)

[ex1.php](https://github.com/thiagodp/validator/tree/master/examples/ex1.php) - Validating values

[ex2.php](https://github.com/thiagodp/validator/tree/master/examples/ex2.php) - Validating arrays

[ex3.php](https://github.com/thiagodp/validator/tree/master/examples/ex3.php) - Validating objects

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity20

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity66

Established project with proven stability

 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 ~20 days

Recently: every ~1 days

Total

16

Last Release

3560d ago

Major Versions

0.5 → 1.02016-08-06

1.0.1 → 2.02016-08-10

### Community

Maintainers

![](https://www.gravatar.com/avatar/154324d722a6ee9c252a0338329781084a97af2d0ea9faaf39176df5a689a2ec?d=identicon)[thiagodp](/maintainers/thiagodp)

---

Top Contributors

[![thiagodp](https://avatars.githubusercontent.com/u/2997844?v=4)](https://github.com/thiagodp "thiagodp (76 commits)")

---

Tags

class-validationphpphputilvalidationvalidatortestingcheckvalidatorvalidationinput

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/phputil-validator/health.svg)

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

###  Alternatives

[osteel/openapi-httpfoundation-testing

Validate HttpFoundation requests and responses against OpenAPI (3+) definitions

1201.9M6](/packages/osteel-openapi-httpfoundation-testing)[nilportugues/assert

A simple and elegant assertion and guard methods library for input validation.

1066.0k7](/packages/nilportugues-assert)[nilportugues/validator

An efficient data validator for PHP

131.5k](/packages/nilportugues-validator)[fahadyousafmahar/slash-login

Say goodbye to repetitively fill / submit login forms during development of your laravel applications. This package allows you to login as any user with just a "slash login" (/login/user\_id)

101.3k](/packages/fahadyousafmahar-slash-login)

PHPackages © 2026

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