fastnorth / validator
FastNorth Validator
This package's canonical repository appears to be gone and the package has been frozen as a result.
Installs: 76 452
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 23
Forks: 5
Open Issues: 0
Requires
- symfony/property-access: ~2.7|~3.2|~4.0
Requires (Dev)
- phpunit/phpunit: ~4.8.0
This package is not auto-updated.
Last update: 2024-01-20 14:32:06 UTC
README
This is a simple data validation library that deals with validating a variety of data structures. It was born out of dissatisfaction with existing libraries that were either very complex and hard to implement, or seemed to have design flaws.
Installation
Simply install through Composer:
composer require fastnorth/validator
Usage
Validating data is a two part process:
- Defining what your data should look like by defining constraints
- Validating that a dataset matches the constraints
The first step is done by creating a Definition, the second by running the data and definition through a Validator.
Definitions
Definitions are specified through a "field" basis. A field can be anything that can be access through Symfony's PropertyAccess Component.
You can either extend Definition or define the constraints on an instance of it:
<?php use FastNorth\Validator\Definition; $definition = new Definition; $definition // Validate [foo] has a minimum string length of 10 characters ->field('[foo]') ->should(new Constraint\StringLength(['min' => 10])) // [bar] has to exist ->field('[bar]') ->required();
Validating
Validation uses the Validator class. It takes a Definition instance in its constructor, and has a validate()
method to validate any data to match the definition. This method returns a Validation instance.
<?php use FastNorth\Validator\Definition; $validator = new Validator($definition); // $yourData = ...; $validation = $validator->validate($yourData); if ($validation->passes()) { // Data matched definition } else { // Validation messages are returned as an array per field foreach($validation->getMessages() as $field => $messagesPerField) { foreach($messagesPerField as $message) { echo $message; } } }