Skip to content

romeOz/rock-validate

Repository files navigation

Validator for PHP

Latest Stable Version Total Downloads Build Status HHVM Status Coverage Status License

Features

  • Supports large many validation rules (string, number, ctype, file, network)
  • Validation of scalar variable and array (attributes())
  • Output the list of errors in an associative array
  • i18n support
  • Hot replacement of placeholders for messages ({{name}} must be valid), as well messages
  • Customization of validation rules
  • Module for Rock Framework

Bolded features are different from Respect/Validation.

Table of Contents

Installation

From the Command Line:

composer require romeoz/rock-validate

In your composer.json:

{
    "require": {
        "romeoz/rock-validate": "*"
    }
}

Quick Start

use rock\validate\Validate;

// Validation length from 10 to 20 characters inclusive + regexp pattern
$v = Validate::length(10, 20, true)->regex('/^[a-z]+$/i');
$v->validate('O’Reilly'); // output: false

$v->getErrors();
/*
output:

[
  'length' => 'value must have a length between 10 and 20',
  'regex' => 'value contains invalid characters'
]
*/

$v->getFirstError();
// output: value must have a length between 10 and 20

####Replacement a placeholder

use rock\validate\Validate;

$v = Validate::length(10, 20, true)
            ->regex('/^[a-z]+$/i')
            ->setPlaceholders(['name' => 'username']);
$v->validate('O’Reilly'); // output: false

$v->getErrors();
/*
output:

[
  'length' => 'username must have a length between 10 and 20',
  'regex' => 'username contains invalid characters',
]
*/

####i18n

use rock\validate\Validate;

$v = Validate::length(10, 20, true)->regex('/^[a-z]+$/i')->setLocale('ru');
$v->validate('O’Reilly'); // output: false

$v->getErrors();
/*
output:

[
  'length' => 'значение должно иметь длину в диапазоне от 10 до 20',
  'regex' => 'значение содержит неверные символы',
]
*/

####As Array or Object

use rock\validate\Validate;

$input = [
    'username' => 'O’Reilly',
    'email' => 'o-reilly@site'
];
$attributes = [
  'username' => Validate::required()
      ->length(10, 20, true)
      ->regex('/^[a-z]+$/i')
      ->setPlaceholders(['name' => 'username']),
  
  'email' => Validate::required()->email()
];

$v = Validate::attributes($attributes);
$v->validate($input); // output false

$v->getErrors();
/*
output:

[
  'username' => [
    'length' => 'username must have a length between 10 and 20',
    'regex' => 'username contains invalid characters',
  ],
  'email' => [
    'email' => 'email must be valid email',
  ]
]
*/

$attribute = 'email';
$v->getFirstError($attribute);
// output: email must be valid

Documentation

Requirements

  • PHP 5.4+

License

The Rock Validate is open-sourced software licensed under the MIT license.