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

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

crysalead/validator
===================

Validation Library

3.0.5(5y ago)313.0k↓26.9%2MITPHPPHP &gt;=5.5

Since Jul 21Pushed 4y ago3 watchersCompare

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

READMEChangelogDependencies (3)Versions (9)Used By (0)

Validator - Validation library
==============================

[](#validator---validation-library)

[![Build Status](https://camo.githubusercontent.com/2cc814e77f933dbbc841df45f1897fb80b47d23039ed3e7156a1bd0ea9fda431/68747470733a2f2f7472617669732d63692e6f72672f63727973616c6561642f76616c696461746f722e706e673f6272616e63683d6d6173746572)](https://travis-ci.org/crysalead/validator)[![Code Coverage](https://camo.githubusercontent.com/784a4d19745d447277ac329e8c594c1a29317965f3f4bc578e4e04e267ba6b28/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f63727973616c6561642f76616c696461746f722f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/crysalead/validator/)

Validator is a flexible and straightforward stand-alone validation library.

### Simple Validation Usage

[](#simple-validation-usage)

```
$v = new Validator();

$v->rule('title', [
    'not:empty',
    'lengthBetween' => ['min' => 3, 'max' => 20]
]);

$v->validate(['title' => 'new title']); // boolean
$v->errors(); // errors ?

```

Each validation rule is defined by an array where the first value is the name of the validation handler. Any name can be prefixed by `'not:'` to match its opposite requirement. The subsequent keys define additional options and the following are the one shared by all validation handler:

- message: The error message displayed if this rule fails.
- required (boolean): Specifies that data for this field must be submitted in order to validate. Defaults to `true`.
- skipEmpty (boolean): Causes the rule to be skipped if the value is null or empty. Defaults to `false`.
- check: The name of a particular validation handler to use, or `'any'` to check them all until one passes.

### Multi-dimensional Arrays Validation

[](#multi-dimensional-arrays-validation)

To validate array the dotted notation can be used like in following:

```
$v = new Validator();
$v->rule('emails.*', 'email');

$v->validate(['emails' => [
    'willy@boy.com', 'johnny@boy.com']
]);
```

It's also possible to validate deeply nested data structures using the same dotted syntax:

```
$v = new Validator();
$v->rule('people.*.email', 'email');

$v->validate([
    'people' => [
        ['email' => 'willy@boy.com'],
        ['email' => 'johnny@boy.com']
    ]
]);
```

### Built-in Validation Handlers

[](#built-in-validation-handlers)

- accepted - must be accepted,
- alphaNumeric - must contain only letters a-z and/or numbers 0-9,
- boolean - must be a boolean,
- creditCard - must be a valid credit card number,
- date - is not a valid date,
- dateAfter - must be date after {:date},
- dateBefore - must be date before {:date},
- dateFormat - must be date with format {:format},
- decimal - must be decimal,
- email - is not a valid email address,
- equalTo - must be the equal to the field `{:key}`,
- empty - must be a empty,
- inList - must contain a valid value,
- inRange - must be inside the range,
- integer - must be an integer,
- ip - must be an ip,
- length - must be longer than {:length},
- lengthBetween - must be between {:min} and {:max} characters,
- lengthMax - must contain less than {:length} characters,
- lengthMin - must contain greater than {:length} characters,
- luhn - must be a valid credit card number,
- max - must be no more than {:max},
- min - must be at least {:min},
- money - must be a valid monetary amount,
- numeric - must be numeric,
- phone - must be a phone number,
- regex - contains invalid characters,
- required - is required,
- time - must be a valid time,
- url - not a URL

All validation can be used with the 'not:' prefix, for example 'not:empty' will fail if the value is empty.

Note: only `'not:empty'`, `'not:inList'` and `'not:inRange'` have a default error message defined so if you intend tu use the `not:` prefix on another validation handler, don't forget to use `->messages()` to set it.

### Adding Custom Validation Rules

[](#adding-custom-validation-rules)

While the validator features a number of handy rules, you'll inevitably want to create your own validation rules. This done (at runtime) by calling `set()` to specify new rule logic.

The simplest form of rule addition is by Regular Expression:

```
$v = new Validator();
$v->set('zeroToNine', '/^[0-9]$/');
```

Often, validation rules come in multiple "formats", for example credit cards, which vary by type of card. Defining multiple formats allows you to retain flexibility in how you validate data.

```
$v = new Validator();
$v->set('postalCode', [
    'us' => '/^\d{5}(?:[-\s]\d{4})?$/',
    'fr' => '/^(F-)?((2[A|B])|[0-9]{2})[0-9]{3}$/',
    'uk' => '/^(GIR|[A-Z]\d[A-Z\d]??|[A-Z]{2}\d[A-Z\d]??)[ ]??(\d[A-Z]{2})$/'
]);

$v->message('postalCode', 'invalid postal code');

$v->rule('zip', 'postalCode');

$v->validate(['zip' => '30700'], ['check' => 'fr']);  // check only the fr validation handler.
$v->validate(['zip' => '30700'], ['check' => 'any']); // default behavior.
```

And if you need more than pattern recognition, you can also supply rules as anonymous functions:

```
$v = new Validator();
$v->set('zeroToNine', function($value, $options = [], &$params = []) {
    return preg_match('/^[0-9]$/', $value);
});
```

### Setting Default Validation Messages

[](#setting-default-validation-messages)

Instead of setting `'message'` for each rule, you can set a default message for each validation handler using `::messages()` like in the following example:

```
$v = new Validator();
$v->set('zeroToNine', '/^[0-9]$/');

Validator::messages([
    'zeroToNine' => 'must be between 0 to 9'
]);

$v->rule('checksum', 'zeroToNine');
$v->validate(['checksum' => '25']);
$v->errors(); // returns ['zeroToNine' => ['must be between 0 to 9']]
```

### Adding Global Validation Rules

[](#adding-global-validation-rules)

The `Validator` class is based on the `Checker` class for performing validations. To add a global validation handler available for all `Validator` instance, you'll need to add it to the `Checker` class instead.

```
Checker::set('zeroToNine', '/^[0-9]$/');
Checker::message('zeroToNine', 'must be between 0 to 9');

$v = new Validator();
$v->rule('checksum', 'zeroToNine');
$v->validate(['checksum' => '25']);
$v->errors(); // returns ['zeroToNine' => ['must be between 0 to 9']]
```

### Customizing Error Messages

[](#customizing-error-messages)

It's sometimes interesting to display some custom data inside error messages. For example some boundaries or a particular label name. To make it work all parameters need to be added to the validation rule like the following:

```
$v = new Validator();

$v->rule('title', [
    'not:empty' => [
        'message' => 'please enter a {:label}',
        'label' => 'title'
    ],
    'lengthBetween' => [
        'min' => 3,
        'max' => 20,
        'message' => 'must be between {:min} and {:max} character long'
    ]
]);
```

### Globalization

[](#globalization)

Since there's a lot of different ways to solve globalization, no assumption on how it should be done have been made. Instead you can define your own error message handler to fit your globalization architecture.

```
$v = new Validator([
    'error' => function($name, $options, $meta = []) {
        $message = __t($options['message'] ?: $name); //
