PHP code example of alksily / validator

1. Go to this page and download the library: Download alksily/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/ */

    

alksily / validator example snippets


use Alksily\Validator\Filter;
use Alksily\Validator\Traits\FilterRules;

class UserFilter extends Filter
{
    use FilterRules;

    // check data for create new user
    public static function add(array &$data = [])
    {
        $filter = new self($data);

        $filter
            ->addGlobalRule($filter->leadEscape()) // global rule for all fields in $data
            ->addGlobalRule($filter->leadTrim())
            ->attr('username')
                ->addRule($filter->checkStrlenMax(20)) // parameter passing for checking
                ->addRule($filter->checkStrlenMin(3))
            ->attr('password')
                ->addRule($filter->checkStrlenBetween(3, 20))
            ->attr('password_again')
                ->addRule($filter->checkEqualToField('password'), 'Passwords do not match') // second arg is reason error
            ->attr('email')
                ->addRule($filter->checkEmail())
            ->attr('ip')
                ->addRule($filter->checkIp());

        return $filter->run();
    }
}

// data example
$data = [
    'username'       => 'Aleksey',
    'password'       => 'MyPassword',
    'password_again' => 'MyPassword',
    'email'          => '[email protected]',
    'ip'             => '127.0.0.1',
];

$result = UserFilter::add($data);

if ($result === true) {
    // check ok
    var_dump($data); // sanitized data
} else {
    // found an error
    var_dump($result);
}
text
array(1) {
  ["password_again"]=>
  string(22) "Passwords do not match"
}