lubaro / php-validator
根据预定义或自定义规则验证字符串、数字和数组。
dev-main
2021-04-26 09:59 UTC
Requires
- php: >=8.0
- phpstan/phpstan: ^0.12.83
- symfony/string: ^5.2
Requires (Dev)
- phpstan/extension-installer: ^1.1
- phpstan/phpstan-phpunit: ^0.12.18
- phpunit/phpunit: ^9.5
- psy/psysh: ^0.10.8
- squizlabs/php_codesniffer: ^3.6
- symfony/var-dumper: ^5.2
This package is auto-updated.
Last update: 2024-09-26 17:13:55 UTC
README
根据预定义或自定义规则验证字符串、数字和数组。
安装
composer require lubaro/php-validator
验证字符串
required()
- 检查字符串是否存在且不为空minLength(int $minLength)
- 检查检查的值长度是否等于或大于传递的最小长度值contains(string $substr)
- 检查检查的值是否包含一次或多次传递的子串
$v = new LubaRo\PhpValidator\Validator(); $stringValidator = $v->string(); // say to validator that we want to validate strings $stringValidator->isValid(''); // => true $stringValidator->required()->isValid(''); // => false $ruleSet1 = $stringValidator->required()->contains('aka'); $ruleSet1->isValid('Checked value aka string value'); // => true $ruleSet1->isValid('Simple string'); // => false
验证数字
required()
- 检查数字是否存在positive()
- 检查数字是否大于零range(int|float $min, int|float $max)
- 检查数字值是否在或等于提供的值之间
$v = new LubaRo\PhpValidator\Validator(); $v->number()->isValid(45.15); // => true $v->number()->isValid('45.15'); // => false $v->number()->range(-4, 15)->isValid(0); // => true
验证数组
required()
- 检查数组是否存在sizeof(int $size)
- 检查数组大小是否等于给定值shape(array $shape)
- 检查数组是否包含指定的元素
$v = new LubaRo\PhpValidator\Validator(); $v->array()->isValid([1, 2, 3]); // => true $v->array()->sizeof(2)->isValid(['name' => 'Pablo', 'age' => 27]); // => true $arrayShape = $v->array()->shape([ 'name' => $v->string()->required(), 'age' => $v->number()->positive() ]); $arrayShape->isValid(['name' => 'Pablo', 'age' => 27, 'hobbies' => []]); // => true $arrayShape->isValid(['name' => 'Jake', 'hobbies' => []]); // => false $arrayShape->isValid(['name' => 'Gary', 'age' => -1800]); // => false
自定义定义的规则
您可以为任何类型的验证器(如字符串、数字或数组)添加自己的规则
$v = new LubaRo\PhpValidator\Validator(); // in custom function first parameter is a validating value // other parameters come after // for custom functions number of parameters is not restricted $fn = fn($checkedNumber, $param1) => $checkedNumber < $param1; // addValidator(validatorName, customFunctionName, function); $v->addValidator('number', 'isLessThan', $fn); // apply custom function using test(customFuncName, ...params) $lessThan15 = $v->number()->required()->test('isLessThan', 15); $lessThan15->isValid(5); // => true $lessThan15->isValid(25); // => false