lubaro/php-validator

根据预定义或自定义规则验证字符串、数字和数组。

dev-main 2021-04-26 09:59 UTC

This package is auto-updated.

Last update: 2024-09-26 17:13:55 UTC


README

GitHub CI

根据预定义或自定义规则验证字符串、数字和数组。

安装

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