PHP code example of volcanus / validation

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

    

volcanus / validation example snippets




    use Volcanus\Validation\Context;
    use Volcanus\Validation\Checker\IntChecker;
    use Volcanus\Validation\Exception\CheckerException;
    use Volcanus\Validation\Exception\CheckerException\IntException;
    use Volcanus\Validation\Exception\CheckerException\MinValueException;
    use Volcanus\Validation\Exception\CheckerException\MaxValueException;

    $checker = new IntChecker();
    try {
        $checker->check('foo', ['min' => 1, 'max' => 10]);
    } catch (IntException $e) {
        die('数値を入力してください');
    } catch (MinValueException $e) {
        die('1以上の数値を入力してください');
    } catch (MaxValueException $e) {
        die('10以下の数値を入力してください');
    }



    $checker = new IntChecker();
    try {
        $checker($data['number'], [
            'min' => 1,
            'max' => 10,
        ]);
    } catch (CheckerException $e) {
        die('1から10までの数値を入力してください');
    }



    $validation = new Context([
        'id'   => 10,
        'name' => '',
    ]);
    $validation->check('id'  , 'notEmpty');
    $validation->check('id'  , 'int' , ['min' => 1, 'max' => 10]);
    $validation->check('name', 'notEmpty');
    $validation->check('name', 'maxLength', ['length' => 10]);



    if ($validation->isValid()) {
        // 正常時の処理
    } else {
        $errors = [];
        if ($validation->isError('id', 'notEmpty')) {
            $errors[] = 'IDを入力してください';
        }
        if ($validation->isError('id', 'int')) {
            $errors[] = 'IDが不正です';
        }
        if ($validation->isError('name', 'notEmpty')) {
            $errors[] = '名前を入力してください';
        }
        if ($validation->isError('name', 'maxLength')) {
            $errors[] = '名前が長すぎます';
        }
    }



    $validation = new Context([
        'id'   => 0,
        'name' => '',
    ]);
    $validation->registerChecker('int', function($value, $options = [])) {
        if (!ctype_digit(strval($value)) ||
            strcmp(strval($value), sprintf('%d', $value)) !== 0
        ) {
            return false;
        }
        if (isset($options[0]) && intval($value) < $options[0]) {
            return false;
        }
        if (isset($options[1]) && intval($value) > $options[1]) {
            return false;
        }
        return true;
    });
    $validation->registerChecker('notEmpty', function($value) {
        return (isset($value) && strlen($value) !== 0);
    });

    $validation->check('id'  , 'int', [1, 10]); // false
    $validation->check('name', 'notEmpty'); // false