balsing/rock-validate

PHP I18N 兼容的灵活验证器。

0.14.1 2020-12-15 08:09 UTC

README

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

功能

  • 支持大量验证规则(字符串、数字、ctype、文件、网络)
  • 标量变量和数组(attributes())验证
  • 以关联数组输出错误列表
  • 支持 i18n
  • 消息占位符的热替换({{name}} 必须有效),以及消息本身
  • 自定义验证规则
  • Rock 框架模块 Rock Framework

加粗功能与 Respect/Validation 不同。

目录

安装

从命令行

composer require romeoz/rock-validate

在你的 composer.json 中

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

快速开始

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

####替换占位符

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' => 'значение содержит неверные символы',
]
*/

####作为数组或对象

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

文档

演示

需求

  • PHP 5.4+

许可证

Rock Validate 是开源软件,采用 MIT 许可证