tflori/verja

用于处理包含外部输入(如表单、JSON数据、查询参数等)的数组的验证工具

v1.2.1 2024-04-03 11:20 UTC

README

Build Status Coverage Status Latest Stable Version Total Downloads License

TL;DR:一个用于验证由外部输入(如表单、JSON数据、查询参数等)填充的数组的验证工具。该名称来自古诺尔斯语,意为“守护者”。

安装

常规方式...

composer require tflori/verja

使用方法

初始化容器,设置输入数据,定义过滤器和服务程序,验证数据,获取数据。

$gate = new Verja\Gate();
$gate->accepts([
    'username' => ['notEmpty', 'strLen:3:20'],
    'password' => ['notEmpty', 'strLen:8'],
    'email' => ['notEmpty', 'email'],
]);

if ($gate->validate($_POST)) {
  // how ever your orm works..
  $user = new User($gate->getData());
  $user->save();
} else {
  $errors = $gate->getErrors();
}

如果您喜欢自动完成,当然可以传递对象。

use Verja\Validator;

$gate->accepts([
    'username' => (new Field())
        ->addValidator(new Validator\NotEmpty())
        ->addValidator(new Validator\StrLen(3, 20)),
    'password' => [new Validator\NotEmpty(), new Validator\StrLen(8)],
    'email' => ['notEmpty', new App\Validator\DomainEmail('my-domain.com')]
]);

有关更多信息,请参阅github.io/verja上的文档。

预定义验证器

在此库中包含以下验证器:

  • After:值必须为 $dateTime 之后的时间日期
  • Alpha:值必须只包含字母字符
  • AlphaNumeric:值必须只包含字母和数字字符
  • Before:值必须为 $dateTime 之前的时间日期
  • Boolean:值必须是布尔值
  • Between:值必须在 $min$max 之间
  • Contains:值必须包含 $subString
  • CreditCard:值必须是一个有效的信用卡号
  • DateTime:值必须是一个有效的日期,格式为 $format
  • EmailAddress:值必须是一个有效的电子邮件地址
  • Equals:字段必须与字段 $opposide 匹配
  • InArray:值必须在 $array 中存在
  • Integer:值必须是整数
  • IpAddress:值必须是一个有效的 $version 版本的IP地址
  • IsArray:值必须是一个数组
  • NotEmpty:值不能为空
  • Numeric:值必须是数字
  • PregMatch:值必须匹配正则表达式 $pattern
  • Slug:值必须只包含slug字符(a-z,0-9,-,_)
  • StrLen:字符串长度从值必须在 $min$max 之间
  • Truthful:转换为布尔值后,值必须是真实的
  • Url:值必须是一个有效的URL

预定义过滤器

此库中包含以下过滤器:

  • Boolean:将整数和字符串值转换为布尔值
  • ConvertCase:将大小写转换为 $mode(大写、小写或标题)
  • DateTime:将字符串从 $format 转换为 DateTime 对象
  • Escape:为在HTML中使用转义特殊字符
  • Integer:将字符串值转换为整数
  • Numeric:将字符串值转换为浮点数或整数
  • PregReplace:将 $pattern 替换为 $replace(替换也可以是一个回调)
  • Replace:将值中的 $search 替换为 $replace
  • Trim:从值中删除 $charcterMask