dhii / validator
一个轻量级、符合标准的验证器实现。
v0.1.0-alpha1
2021-01-14 22:19 UTC
Requires
- php: ^7.1 | ^8.0
- dhii/validation-interface: ^0.3.0-alpha3
Requires (Dev)
- phpunit/phpunit: ^7.1 | ^8.0 | ^9.0
- slevomat/coding-standard: ^6.0
- vimeo/psalm: ^3.11.7 | ^4.0
This package is auto-updated.
Last update: 2024-09-22 19:37:58 UTC
README
这是 dhii/validation-interface
的一个轻量级、符合标准的验证器实现。
详细信息
这是一个超轻量级的验证库,允许轻松创建任意深度的验证结构。
示例
一个验证器确保值是有效的用户名。它是一个复合验证器,由2个简单验证器组成
- 确保值是字母数字字符串。
- 确保值长度小于或等于30个字符。
当验证失败时,此验证器层次结构会抛出一系列异常
- 复合验证器失败异常报告发生了多少次失败,并暴露来自简单验证器的失败异常。
- 然后它们会报告具体是什么无效。
use Dhii\Validation\Exception\ValidationFailedExceptionInterface;use Dhii\Validator\CallbackValidator; use Dhii\Validator\CompositeValidator; $alphanum = new CallbackValidator(function ($value) { if (preg_match('![^\d\w]!', $value, $matches)) { return sprintf('Value "%1$s" must be alphanumeric, but contains char "%2$s"', $value, $matches[0][0]); } }); $chars30 = new CallbackValidator(function ($value) { $length = strlen($value); if (!($length <= 30)) { return sprintf('Value "%1$s" is limited to 30 characters, but is %2$d characters long', $value, $length); } }); $usernameValidator = new CompositeValidator([$alphanum, $chars30]); // Valid username: nothing happens $usernameValidator->validate('abcdef'); // Invalid username value: exception thrown try { $percentValidator->validate('abcdefghijklmnopqrstuvwxyz!@#$%'); } catch (ValidationFailedExceptionInterface $e) { // Validation failed with 2 errors. echo $e->getMessage(); // 1: Value "abcdefghijklmnopqrstuvwxyz!@#$%" must be alphanumeric, but contains char "!" // 2: Value "abcdefghijklmnopqrstuvwxyz!@#$%" is limited to 30 characters, but is 31 characters long foreach ($e->getValidationErrors() as $error) { echo (string) $error; } }