dsheiko/validate

Validation library for testing primitive and complex types against a contract

v1.1.0 2018-02-07 14:47 UTC

This package is not auto-updated.

Last update: 2024-04-22 05:50:25 UTC


README

Latest Stable Version Total Downloads License Build Status

Extendable validation library for testing primitive and complex types (including key-value arrays) against a contract

Installation

Require as a composer dependency:

composer require "dsheiko/validate"

Highlights

  • Validators are dead simple to extend
  • It's really easy to validate precondition/postcondition contracts
  • Validator assertions are directly accessible
  • Validation of nested arrays

Usage

Examples

Design by Contract

<?php
use \Dsheiko\Validate;

function login($email, $password)
{
    Validate::contract([
      "email" => [ $email, "IsEmailAddress" ],
      "password" => [ $password, [ "IsString"=> [ "minLength" => 6, "maxLength" => 32, "notEmpty" => true ] ] ],
    ]);
    // do login
}

may throw

  • Dsheiko\Validate\IsString\Exception
  • Dsheiko\Validate\IsString\minLength\Exception
  • Dsheiko\Validate\IsString\maxLength\Exception
  • Dsheiko\Validate\IsEmail\Exception

with a message like

  • Parameter "email" validation failed: "jon#snow.i.." is not a valid email address
  • Parameter "password" validation failed: "123" is too short; must be more than 6 chars

Map Validation

<?php

$params = [
  "email" => "jon#snow.io",
  "password" => "******",
];

Validate::map($params, [
    "email" => ["mandatory", "IsEmailAddress"],
    "password" => ["mandatory", "IsString" => ["minLength" => 6, "maxLength" => 128]],
    "rememberMe" => ["optional", "IsBool" ],
]);

Exception messages look like:

  • Property "email" validation failed: "jon#snow.i.." is not a valid email address