kilbiller/jarvis

一种简单但强大的方式来验证PHP中的数据。

v0.1.4 2020-08-24 14:43 UTC

This package is auto-updated.

Last update: 2024-09-25 00:22:46 UTC


README

CircleCI codecov

一种简单但强大的方式来验证PHP中的数据。

需要php >= 7.0

为什么?

我需要能够轻松创建复杂的验证逻辑,并获取与键关联的错误信息的格式化数组。我没有找到满足这些要求的东西,所以我创建了Jarvis。

功能

  • 流畅的接口
  • 将自定义验证逻辑视为一等公民。它们只是函数!!
  • 以简单数组获取验证错误,每个错误都与输入名称相关联。仅保留每个字段的第一个错误。

API

验证器

->addRule($key: string, $validationFunction: Function | [$validationFunction: Function], $message: string): void
$key: Can be nested (i.e. 'user.firstname').
$validationFunction: Can accept two parameter: the value corresponding to the key currently validated and the whole array. Should return a boolean.
$message: The error message, ${key} will be replaced by the key. Default message is : '${key} is not valid.'

->validate($dataToValidate: array): boolean

->getErrors(): array
->getErrors($dataToValidate: array): array

示例

use Jarvis\Validator;
use function Jarvis\rules\{between, lengthBetween, noWhiteSpace};

$data = ['age' => 45, 'firstname' => 'Jonathan', 'lastname' => 'Blow'];
$data2 = ['age' => 53, 'firstname' => 'Johnny', 'lastname' => 'Depp'];

$validator = (new Validator())
->addRule('age', between(15, 48));
->addRule('firstname', function ($firstname) {
	return $firstname === 'Jonathan';
}, '${key} is not Jonathan.');
->addRule('lastname', [noWhiteSpace(), lengthBetween(0, 50)]),

$validator->validate($data); // -> true
$validator->getErrors(); // -> []

$validator->validate($data2); // -> false
$validator->getErrors(); // -> ['age' => 'age is not valid.', 'firstname' => 'firstname is not Jonathan.']

内置规则

  • between(min, max)
  • isBoolean()
  • isDate(format = 'Y-m-d')
  • isJson()
  • isNull()
  • isNumber()
  • isPositive()
  • isUppercase()
  • isString()
  • lengthBetween(min, max)
  • matchRegex(regex)
  • notEmpty()
  • noWhiteSpace()
  • oneOf(...$functions)

技巧

对于单个键应用多个验证规则有两种方式

  • 使用验证函数数组 -> 这样你只能使用一个错误消息
  • 多次调用 addRule 并使用相同的键 -> 这样你可以更精确地错误消息

所有函数都是柯里化的,因此你可以不传递任何参数(除了 '\Jarvis\rules\isNumber')来内置规则。

use Jarvis\Validator;
use function Jarvis\rules\isNumber;

$validator = (new Validator())
->addRule('age', isNumber());

待办事项

  • 接受对象
  • 添加更多默认规则