ride/lib-validation

Validation library of the Ride framework

1.6.0 2024-06-26 09:10 UTC

README

Validation library of the PHP Ride framework.

What's In This Library

Filters

The Filter interface is used to pre-process a value to fix input automatically. A filter should return the original value if it can't handle the input type.

Different implementations are available.

AllowCharacterFilter (characters)

Filters all non-allowed characters from a string.

This filter has the following option:

  • characters: all allowed characters, characters not found in this string, will be trimmed out (string)

LowerCaseFilter (lower)

Transforms all upper case characters to lower case.

This filter has no options.

ReplaceFilter (replace)

Replaces values in a string.

This filter has the following options:

  • search: string to search for (string)
  • replacement: replacement for the matches of search (string|optional)

SafeStringFilter (safeString)

  • replacement: replacement for special characters, defaults to - (string|optional)
  • lower: transform to lower case, defaults to true (boolean|optional)

StripTagsFilter (stripTags)

Strips HTML and PHP tags from a string, using PHP's internal strips_tags function

This filter has the following option:

  • allowedTags: a set of html tags that are allowed and won't be stripped, for example: <p><strong>.

TrimFilter (trim)

Trims the provided value from spaces.

This filter has the following options:

  • trim.lines: trim all lines, or values if the provided value is an array (boolean|optional)
  • trim.empty: remove empty lines or values, only when trim.lines is enabled (boolean|optional)

UpperCaseFilter (upper)

Transforms all lower case characters to upper case.

This filter has no options.

Validators

The Validator interface is used to validate a single value.

Different implementations are available.

ClassValidator (class)

Checks if the provided string is a valid class name

This validator has the following options:

  • class: class which the provided class should implement or extend (string|optional)
  • required: flag to see if a value is required (boolean|optional)

This validator generates the following errors:

  • error.validation.class: default error message
  • error.validation.class.extends: when the class does not extend the required class
  • error.validation.class.implements: when the class does not implement the required interface

DsnValidator (dsn)

Checks if the provided string is a valid DSN.

This validator has the following option:

  • required: flag to see if a value is required (boolean|optional)

This validator generates the following errors:

  • error.validation.dsn: default error message (string|optional)
  • error.validation.required: required error message (string|optional)

EmailValidator (email)

Checks if the provided value is a valid email address.

This validator has the following option:

  • required: flag to see if a value is required (boolean|optional)

This validator generates the following errors:

  • error.validation.email: default error message
  • error.validation.required: required error message

FileExtensionValidator (extension)

Checks if the provided path string has an allowed extension.

This validator has the following options:

  • extensions: allowed extensions (array)
  • required: flag to see if a value is required (boolean|optional)

This validator generates the following errors:

  • error.validation.file.extension: default error message
  • error.validation.required: required error message

JsonValidator (json)

Checks if the json string is valid.

This validator has the following options:

  • required: flag to see if a value is required (boolean|optional)

This validator generates the following errors:

  • error.validation.json: default error message
  • error.validation.required: required error message

MinMaxValidator (minmax)

Checks if the provided numeric value is in the provided range.

This validator has the following options:

  • error.minimum: error code when the value is less then minimum (string|optional)
  • error.maximum: error code when the value is more then maximum (string|optional)
  • error.minimum.maximum: error code when the value is not between minimum and maximum (string|optional)
  • error.numeric: error code when the value is not numeric (string|optional)
  • minimum: minimum value (numeric|optional)
  • maximum: maximum value (numeric|optional)
  • required: flag to see if a value is required (boolean|optional)

Note: Minimum and maximum are both optional both at least one of them is required. The values for minimum and maximum are included in the range.

This validator generates the following errors:

  • error.validation.minimum: when the value is less then the provided minimum
  • error.validation.maximum: when the value is greater then the provided maximum
  • error.validation.minmax: when the value is less then the provided minimum or greater then the provided maximum
  • error.validation.required: required error message

NumericValidator (numeric)

Checks if the provided value is a numeric value.

This validator has the following options:

  • error.numeric: error code when the value is not numeric (string|optional)
  • required: flag to see if a value is required (boolean|optional)

This validator generates the following error:

  • error.validation.numeric: default error message
  • error.validation.required: required error message

RegexValidator (regex)

Checks if the provided string matches a regular expression.

This validator has the following options:

  • error.regex: error code when the value did not match the regular expression (string|optional)
  • error.required: error code when the required value was empty (string|optional)
  • regex: regular expression to match (string)
  • required: flag to see if a value is required (boolean|optional)

This validator generates the following errors:

  • error.validation.regex: default error message
  • error.validation.required: required error message

RequiredValdiator (required)

Checks if a value is provided

This validator has the following option:

  • error.required: error code when no value is provided (string|optional)

This validator generates the following error:

  • error.validation.required: required error message

SizeValidator (size)

Checks if the length of the provided string or the size of the provided array.

This validator has the following options:

  • minimum: minimum value (numeric|optional)
  • maximum: maximum value (numeric|optional)

Note: Minimum and maximum are both optional both at least one of them is required. The values for minimum and maximum are included in the range.

This validator generates the following errors:

  • error.validation.maximum.array: when the number of array elements is greater then the provided maximum
  • error.validation.maximum.string: when the size of a string is greater then the provided maximum
  • error.validation.minimum.array: when the number of array elements is less then the provided minimum
  • error.validation.minimum.string: when the size of a string is less then the provided minimum
  • error.validation.minmax.array: when the number of array elements is less then the provided minimum or greater then the provided maximum
  • error.validation.minmax.string: when the size of a string is less then the provided minimum or greater then the provided maximum
  • error.validation.object: when the value is an object

UrlValidator (url)

Checks if the provided string is a valid URL.

This validator has the following option:

  • required: flag to see if a value is required (boolean|optional)

This validator generates the following errors:

  • error.validation.required: required error message
  • error.validation.url: default error message

WebsiteValdiator (website)

Checks if the provided string is a valid website. This is the same as the URL validator but limited to http(s)://.

This validator has the following option:

  • required: flag to see if a value is required (boolean|optional)

This validator generates the following errors:

  • error.validation.required: required error message
  • error.validation.website: default error message

Constraints

The Constraint interface is used to validate a data container. A data container can be an array or an object.

Different implementations are available.

GenericConstraint (generic)

The GenericConstraint is a combination of filters and validators which can be applied on specific properties of the data container.

<?php

use ride\library\validation\factory\ValidationFactory;

function foo(ValidationFactory $factory) {
    $trimFilter = $factory->createFilter('trim');
    $requiredValidator = $factory->createValidator('required');
    
    $constraint = $factory->createConstraint('generic');
    $constraint->addFilter($trimFilter, 'name');
    $constraint->addFilter($trimFilter, 'description');
    $constraint->addValidator($requiredValidator, 'name');
    $constraint->addValidator($requiredValidator, 'description');
    
    return $constraint;
}

This constraint will trim and require the name and description properties to pass.

OrConstraint (or)

The OrConstraint defines a set of properties for which at least one has to be provided. When constraining, it will add a validation error to all properties when none of them is provided.

<?php

use ride\library\validation\factory\ValidationFactory;

function foo(ValidationFactory $factory) {
    $constraint = $factory->createConstraint('or');
    $constraint->addProperty('firstName');
    $constraint->addProperty('displayName');
    
    // optionally, you can override the default error code
    $constraint->setError('error.validation.custom');
    
    return $constraint;
}

This constraint will fail when both firstName and displayName are empty.

EqualsConstraint (equals)

The EqualsConstraint defines a set of properties which have to have the same value. Usefull when asking to repeat a new password.

<?php

use ride\library\validation\factory\ValidationFactory;

function foo(ValidationFactory $factory) {
    $constraint = $factory->createConstraint('equals');
    $constraint->addProperty('password');
    $constraint->addProperty('repeatPassword');
    
    // optionally, you can override the default error code
    $constraint->setError('error.validation.custom');
    
    return $constraint;
}

This constraint will fail when password and repeatPassword are not the same value.

ConditionalConstraint (conditional)

The ConditionalConstraint is a generic constraint which only validates when defined properties contain a specific value. Usefull for properties which are dependant on a type or status.

<?php

use ride\library\validation\factory\ValidationFactory;

function foo(ValidationFactory $factory) {
    $requiredWebsiteValidator = $factory->createValidator('website', array('required' => true));
    
    $constraint = $factory->createConstraint('conditional');
    $constraint->addValueCondition('type', 'url');
    $constraint->addValidator($requiredWebsiteValidator, 'url');
    
    return $constraint;
}

This constraint will require the url property when the type property is set to "url".

ChainConstraint (chain)

The ChainConstraint is used to combine different constraints together into one. Usefull to build a full validation for a complex data type.

<?php

use ride\library\validation\factory\ValidationFactory;

function createConstraint(ValidationFactory $factory) {
    $trimFilter = $factory->createFilter('trim');
    $requiredValidator = $factory->createValidator('required');
    $requiredWebsiteValidator = $factory->createValidator('website', array('required' => true));
    
    $generalConstraint = $factory->createConstraint('generic');
    $generalConstraint->addFilter($trimFilter, 'name');
    $generalConstraint->addFilter($trimFilter, 'description');
    $generalConstraint->addValidator($requiredValidator, 'name');
    $generalConstraint->addValidator($requiredValidator, 'description');
    $generalConstraint->addValidator($requiredValidator, 'type');
    
    $typeUrlConstraint = $factory->createConstraint('conditional');
    $typeUrlConstraint->addValueCondition('type', 'url');
    $typeUrlConstraint->addFilter($trimFilter, 'url');
    $typeUrlConstraint->addValidator($requiredWebsiteValidator, 'url');
    
    $typeNodeConstraint = $factory->createConstraint('conditional');
    $typeNodeConstraint->addValueCondition('type', 'node');
    $typeNodeConstraint->addValidator($requiredWebsiteValidator, 'node');
    
    $chain = $factory->createConstraint('chain');
    $chain->addConstraint($generalConstraint);
    $chain->addConstraint($typeUrlConstraint);
    $chain->addConstraint($typeNodeConstraint);
    
    return $chain;
}

This constrain will trim and require the name and description property. The type property is also required. When the value for the type property is "url", the url property is required after being trimmed. The same for the node property when the value of the type property is "node".

ValidationFactory

The ValidationFactory is used to construct new validation instances from this library. You can use is to create filters, validators and constraints on a name basis.

ValidationError

A ValidationError is an error of a single validator. Validators will keep the errors of the last validate call. Constraints will gather the occured errors and collect them in a ValidationException.

ValidationException

A ValidationException is thrown by the constraint implementations after validation is done. It contains all the occured errors which can be obtained in their entirety or only for specific properties.

Code Sample

<?php

use ride\library\validation\exception\ValidationException;
use ride\library\validation\factory\ValidationFactory;

function foo(ValidationFactory $factory) {
    // filter some values
    $trimFilter = $factory->createFilter('trim');
    
    $result = $trimFilter->filter(null); // null
    $result = $trimFilter->filter($trimFilter); // $trimFilter
    $result = $trimFilter->filter('  My Title  '); // 'My Title'
    
    // validate some values
    $requiredValidator = $factory->createValidator('required');
    
    $result = $requiredValidator->isValid(null); // false
    $result = $requiredValidator->isValid($requiredValidator); // true
    
    // constrain a data container
    // we're using an array but this can be an object with getters and setters as well
    $data = array(
        'title' => ' My Title  ',
        'description' => null,
        'type' => 'url',
        'node' => null,
        'url' => null,
    );
    
    // see the chain constraint sample for the chain build up
    $constraint = createConstraint($factory);
    
    try {
        $result = $contraint->constrain($data);
    } catch (ValidationException $exception) {
        // url is required in this situation
        $result = $exception->getAllErrors();
        $result = $exception->getErrors('url');
    }
}

Implementations

For more examples, you can check the following implementation of this library:

Installation

You can use Composer to install this library.

composer require ride/lib-validation