district5/validator

2.1.0 2024-09-03 08:02 UTC

This package is auto-updated.

Last update: 2024-09-03 08:03:14 UTC


README

codecov

District5 验证库

关于

此库提供了支持验证器的骨架。

安装

此库不需要其他库。

composer require district5/validator

用法

验证器

要创建验证器的实现,您需要实现接口 \District5\Validator\ValidatorInterface 或扩展提供的抽象类 \District5\Validator\AbstractValidator

一个StringLength验证器的示例验证器可能如下所示

use \District5\Validator\AbstractValidator;

class StringLengthValidator extends AbstractValidator
{
    protected $errorMessages = [
        'notString' => 'Value is not a string',
        'tooShort' => 'Value is below the minimum string length',
        'tooLong' => 'Value exceeds the maximum string length'
    ];

    private $min;

    private $max;

    public function __construct(int $min, int $max)
    {
        parent::__construct();

        $this->min = $min;
        $this->max = $max;
    }

    public function isValid($value): bool
    {
        if (!is_string($value)) {
            $this->setLastErrorMessage('notString');
            return false;
        }

        $len = strlen($value);

        if ($len > $this->max) {
            $this->setLastErrorMessage('tooLong');
            return false;
        }

        if ($len < $this->min) {
            $this->setLastErrorMessage('tooShort');
            return false;
        }

        return true;
    }
} 

问题

记录一个错误报告!