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

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

chippyash/validation
====================

comprehensive function based validation routines

3.0.0(6y ago)010.8k21BSD-3-ClausePHPPHP &gt;=7.2

Since Mar 3Pushed 6y ago1 watchersCompare

[ Source](https://github.com/chippyash/Validation)[ Packagist](https://packagist.org/packages/chippyash/validation)[ Docs](http://zf4.biz/packages?utm_source=packagist&utm_medium=web&utm_campaign=blinks&utm_content=validation)[ RSS](/packages/chippyash-validation/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependencies (7)Versions (15)Used By (1)

chippyash/validation
====================

[](#chippyashvalidation)

Quality Assurance
-----------------

[](#quality-assurance)

[![PHP 7.2](https://camo.githubusercontent.com/5180a354acf28fb748fbeddd95219b60e0145d1e0eac9f976ca9a1bc9bc0337b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d372e322d626c75652e737667)](https://camo.githubusercontent.com/5180a354acf28fb748fbeddd95219b60e0145d1e0eac9f976ca9a1bc9bc0337b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d372e322d626c75652e737667)[![Build Status](https://camo.githubusercontent.com/4e63ac83defc8116e36965bd27472e86c655fb8d0b5214c348a75db401f6adfa/68747470733a2f2f7472617669732d63692e6f72672f6368697070796173682f56616c69646174696f6e2e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/chippyash/Validation)[![Test Coverage](https://camo.githubusercontent.com/4548eeecf7d31ffe0b7f07734bf442120793050d4cecc115a6142e7d44301256/68747470733a2f2f636f6465636c696d6174652e636f6d2f6769746875622f6368697070796173682f56616c69646174696f6e2f6261646765732f636f7665726167652e737667)](https://codeclimate.com/github/chippyash/Validation/coverage)[![Code Climate](https://camo.githubusercontent.com/f2c6831c9895fe79ccf7c0e295dffaaea547f2afd10818159d2ecfdfe115a721/68747470733a2f2f636f6465636c696d6174652e636f6d2f6769746875622f6368697070796173682f56616c69646174696f6e2f6261646765732f6770612e737667)](https://codeclimate.com/github/chippyash/Validation)

The above badges represent the current development branch. As a rule, I don't push to GitHub unless tests, coverage and usability are acceptable. This may not be true for short periods of time; on holiday, need code for some other downstream project etc. If you need stable code, use a tagged version. Read 'Further Documentation' and 'Installation'.

Please note that developer support for PHP5.4 &amp; 5.5 was withdrawn at version 2.0.0 of this library. If you need support for PHP 5.4 or 5.5, please use a version `>=1,isValid('128.0.0.1);  //return false
```

You can construct a Netmask Validator with a single CIDR address mask or an array of them. If you call the Netmask isValid (or invoke it) with a null IP, It will try to get the IP from $\_SERVER\['REMOTE\_ADDR'\] or $\_SERVER\['HTTP\_X\_FORWARDED\_FOR'\] thus making it ideal for its' primary use case, that of protecting your web app against requests from unauthorised IP addresses.

For more uses of the Netmask validator, see the test cases.

- Chippyash\\Validation\\Common\\UKPostCode: Simple extension of Zend PostCode to check for UK Post Codes. Should be straightforward to create your own country specific validator;
- Chippyash\\Validation\\Common\\UKTelNum. Again, a simple extension of the Zend TelNum Validator
- Chippyash\\Validation\\Common\\ZFValidator: A Simple class allowing you to extend it to create any validator using the Zend Validators.

### Complex Validators

[](#complex-validators)

Here is where we start to depart from the Zend validators.

- Chippyash\\Validation\\Common\\ArrayPart. Is the value an array, does the required key exist, and does it validate according to the passed in function parameter?

```
    use Chippyash\Validation\Common\ArrayPart;
    use Chippyash\Validation\Common\Enum;

    $validator = new ArrayPart('idx', new Enum(['foo','bar']));
    $ret = $validator->isValid(['idx' => 'bop']); //false
    $ret = $validator->isValid(['foo' => 'bop']); //false
    $ret = $validator->isValid(['idx' => 'bar']); //true
```

- Chippyash\\Validation\\Common\\Lambda. The Lambda validator expects a function on construction that will accept a value and return true or false:

```
    use Chippyash\Validation\Common\Lambda;

    $validator = new Lambda(function($value) {
        return $value === 'foo';
    });

    $ret = $validator->isValid('bar'); //false
```

You can pass in an optional second StringType parameter with the failure message

```
    use Chippyash\Validation\Common\Lambda;
    use Chippyash\Type\String\StringType;

    $validator = new Lambda(function($value) {
        return $value === 'foo';
    },
        new StringType('Oops, not a Foo');

    if (!$validator->isValid('bar')) { //false
        $errMsg = implode(' : ', $validator->getMessages());
    }
```

You can specify a Messenger parameter as the second parameter to your function declaration if you want to handle adding error messages manually

```
    use Chippyash\Validation\Messenger;
    use Chippyash\Validation\Common\Lambda;

    $validator = new Lambda(function($value, Messenger $messenger) {
            if ($value != 'foo') {
                $messenger->add('error message');
                return false;
            }
            return true;
        }
    );
```

- Chippyash\\Validation\\Common\\ISO8601DateString: Does the supplied string conform to an ISO8601 datestring pattern. *docs tbc*. This validator is so complex, that it probably deserves it's own library. So be warned, it may be removed from this one!

### Pattern Validators

[](#pattern-validators)

Pattern validators allow you to validate complex data structures. These data structures will normally be a traversable (array, object with public parameters, object implementing a traversable interface etc.) They are central to the usefulness of this library.

For example, lets say we have some incoming Json:

```
$json = '
{
    "a": "2015-12-01",
    "b": false,
    "c": [
        {
            "d": "fred",
            "e": "NN10 6HB"
        },
        {
            "d": "jim",
            "e": "EC1V 7DA"
        },
        {
            "d": "maggie",
            "e": "LE4 4HB"
        },
        {
            "d": "sue",
            "e": "SW17 9JR"
        }
    ],
    "f": [
        "a@b.com",
        "c@d.co.uk"
    ]
}
';

```

The first thing we'll do is convert this into something PHP can understand, i.e.

```
    $value = json_decode($json);  //or use the Zend\Json class for solid support
```

#### HasTypeMap

[](#hastypemap)

The HasTypeMap validator allows us to validate both the keys and the values of our incoming data and thus forms the heart of any complex validation requirement.

```
use Chippyash\Validation\Pattern\HasTypeMap;
use Chippyash\Validation\Common\ISO8601DateString;
use Chippyash\Validation\Common\IsArray;
use Chippyash\Validation\Common\Email;

$validator = new HasTypeMap([
    'a' => new ISO8601DateString(),
    'b' => 'boolean',
    'c' => new IsArray(),
    'f' => new IsArray()
]);

$ret = $validator->isValid($value);
```

Note, again, the best we can do for the 'c' and 'f' element is determine if it is an array. See the 'Repeater' below for how to solve this problem.

The values supplied in the TypeMap can be one of the following:

- Any returned by PHP gettype(), i.e. "integer" "double" "string", "boolean", "resource", "NULL", "unknown"
- The name of a class, e.g. '\\Chippyash\\Type\\String\\StringType'
- A function conforming to the signature 'function($value, Messenger $messenger)' and returning true or false
- An object implementing the ValidationPatternInterface

#### Repeater

[](#repeater)

The Repeater pattern allows us to validate a non associative array of values. Its constructor is:

```
__construct(ValidatorPatternInterface $validator, IntType $min = null, IntType $max = null)
```

If $min === null, then it will default to 1. If $max === null, then it will default to -1, i.e. no max.

We can now rewrite our validator to validate the entire input data:

```
use Chippyash\Validation\Pattern\HasTypeMap;
use Chippyash\Validation\Pattern\Repeater;
use Chippyash\Validation\Common\ISO8601DateString;
use Chippyash\Validation\Common\IsArray;
use Chippyash\Validation\Common\Email;
use Chippyash\Validation\Common\UKPostCode;

$validator = new HasTypeMap([
    'a' => new ISO8601DateString(),
    'b' => 'boolean',
    'c' => new Repeater(
        new HasTypeMap([
            'd' => 'string',
            'e' => new UKPostCode()
        ]),
        null,
        4
    ),
    'f' => new Repeater(new Email())
]);

$ret = $validator->isValid($value);
```

This says that the 'c' element must contain 1-4 items conforming to the given TypeMap. You can see this in action in the examples/has-type-map.php script.

### Logical Validators

[](#logical-validators)

These validators allow you carry out boolean logic. LAnd, LOr, LNot and LXor do as expected.

Each require ValidatorPatternInterface constructor parameters. Here is superficial example:

```
    use Chippyash\Validation\Logical;
    use Chippyash\Validation\Common\Lambda;

    $true = new Lambda(function($value){return true;});
    $false = new Lambda(function($value){return false;});

    $and = new Logical\LAnd($true, $false);
    $or = new Logical\LOr($true, $false);
    $not = new Logical\LNot($true);
    $xor = new Logical\LXor($true, $false);
```

And of course, you can combined them:

```
    $validator = new Logical\LNot( new Logical\LAnd($true, Logical\LXor($false, $true)))
    $ret = $validator->isValid('foo');

    //the above is equivelent to
    $ret = !( true && (false xor true))
```

The real power of this is that it allows you to create alternate validation:

```
    $nullOrDate = new LOr(
        new Lambda(function($value) {
            return is_null($value);
        },
        new Lambda(function($value) {
            try {new \DateTime($value); return true;} catch (\Exception $e) { return false;}
        })
    );
```

### Validation Processor

[](#validation-processor)

All the above assumes you are running a single validation on the data and that all of the items specified by the validator pattern exist in the incoming data. What happens when you have optional items? This is where the ValidationProcessor comes in.

ValidationProcessor allows you to run a number of validation passes over the data. Typically, you'd run a validation for all required data items first, and then run one or more subsequent validations checking for optional items.

To use, construct the processor with your first (usually required item) validator, then simply add additional ones to it.

```
$validator = new ValidationProcessor($requiredValidator);
$validator->add($optionalValidator);
```

Run your validation and gather any error messages if required:

```
if (!$validator->validate($value)) {
    var_dump($validator->getMessenger()->implode());
}
```

The processor will run each validation in turn and return the combined result. See examples/validation-processor.php for more illustration.

Further documentation
---------------------

[](#further-documentation)

Please note that what you are seeing of this documentation displayed on Github is always the latest dev-master. The features it describes may not be in a released version yet. Please check the documentation of the version you Compose in, or download.

[Test Contract](https://github.com/chippyash/Validation/blob/master/docs/Test-Contract.md) in the docs directory.

Check out [ZF4 Packages](http://zf4.biz/packages?utm_source=github&utm_medium=web&utm_campaign=blinks&utm_content=validation) for more packages

### UML

[](#uml)

Changing the library
--------------------

[](#changing-the-library)

1. fork it
2. write the test
3. amend it
4. do a pull request

Found a bug you can't figure out?

1. fork it
2. write the test
3. do a pull request

NB. Make sure you rebase to HEAD before your pull request

Or - raise an issue ticket.

Where?
------

[](#where)

The library is hosted at [Github](https://github.com/chippyash/Validation). It is available at [Packagist.org](https://packagist.org/packages/chippyash/validation)

### Installation

[](#installation)

Install [Composer](https://getcomposer.org/)

#### For production

[](#for-production)

```
    "chippyash/validation": ">=3,
