PHP code example of district5 / validator

1. Go to this page and download the library: Download district5/validator library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

district5 / validator example snippets



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;
    }
}