PHP code example of githusband / validation

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

    

githusband / validation example snippets


$validation->set_rules("

// 名字是必要的,必须是字符串,长度必须大于3且小于等于32
"name" => "数全称即可
"name" => "*|string|length><=[3,32]"

// id 是必要的,且必须是数字
"id" => "

$rule = [
    // 标准写法
    "*" => "unique(@this,@parent)",
    // 省略 `@this`
    "*" => "unique[@parent]",
    // 默认参数写法
    "*" => "unique"
];

$validation->add_method('check_id', function ($id) {
    if ($id == 0) {
        return false;
    }

    return true;
}, 'c_id');

$rule = [
    // 必要的,且只能是数字,且必须大于 0
    "id" => "

/**
 * 推荐用 rule class 增加验证方法
 * 如果需要定义方法标志,将他们放在 method_symbols 属性中
 */
class RuleClassTest
{
    // 方法标志
    public static $method_symbols = [
        'is_custom_string' => 'cus_str',
    ];

    // 方法
    public static function is_custom_string($data)
    {
        return preg_match('/^[\w\d -]{8,32}$/', $data) ? true : false;
    }
}

use RuleClassTest;

// 注册一个新的方法类,RuleClassTest
$validation->add_rule_class(RuleClassTest::class);

use githusband\Validation;
use RuleClassTest;

class MyValidation extends Validation
{
    protected $rule_classes = [
        RuleClassTest::class
    ];
}

$rule = [
    // 必要的,且格式必须是 /^[\w\d -]{8,32}$/
    "id" => "

/**
 * 1. 推荐用 trait 拓展验证方法
 * 如果需要定义方法标志,将他们放在属性中,属性命名规则:“method_symbols_of_” + 类名(大驼峰转下划线)
 */
trait RuleExtendTrait
{
    // 方法标志
    protected $method_symbols_of_rule_extend_trait = [
        'euqal_to_1' => '=1',
    ];

    // 方法
    protected function euqal_to_1($data)
    {
        return $data == 1;
    }
}

use githusband\Validation;

class MyValidation extends Validation
{
    // 1. 使用 Trait
    use RuleExtendTrait;

    /**
     * 2. 直接增加验证方法及其标志
     * 如果需要定义方法标志,将他们放在属性 method_symbols 中
     */
    protected $method_symbols = [
        'grater_than_or_equal_to_1' => '>=1',
    ];

    protected function grater_than_or_equal_to_1($data)
    {
        return $data >= 1;
    }
}

$rule = [
    // id 必要的,且必须大于等于 1
    "id" => "ptional|euqal_to_1",
];

public static $method_symbols = [
    'is_custom_string' => 'cus_str',
];

class RuleClassTest
{
    /**
     * 方法标志:
     * - 如果值为字符串,则表示标志。
     * - 如果值为数组,则支持以下字段:
     *   - `symbols`: 表示标志
     *   - `is_variable_length_argument`: 默认为 false。表示方法第二个参数为可变长度参数,规则集 中的第一个参数之后的所有参数都会被第二个参数的子元素。参考 `githusband\Rule\RuleClassDefault::$method_symbols['in_number_array']`。
     *   - `default_arguments`: 默认为 无。设置方法的默认参数。参考 `githusband\Rule\RuleClassArray::$method_symbols['is_unique']`。
     *     - `default_arguments` 数组的键必须是整形数字,表示第几个默认参数. 例如,`2` 表示第二个参数。
     *     - `default_arguments` 数组的值可以是任意值。对于类似 "@parent" (表示当前字段的父数据),参考 https://github.com/gitHusband/Validation?tab=readme-ov-file#43-%E6%96%B9%E6%B3%95%E4%BC%A0%E5%8F%82
     * 
     * @example `in_number_array[1,2,3]` 第二个参数是一个数组 `[1,2,3]`
     * @see githusband\Rule\RuleClassDefault::$method_symbols
     * @see githusband\Rule\RuleClassArray::$method_symbols
     * @var array<string, string|array>
     */
    public static $method_symbols = [
        'is_custom_string' => 'cus_str',
        'is_in_custom_list' => [
            'symbols' => '<custom>',
            'is_variable_length_argument' => true,  // 第一个参数之后的所有参数,都被认作第二个参数数组的子元素
        ],
        'is_equal_to_password' => [
            'symbols' => '=pwd',
            'default_arguments' => [
                2 => '@password'    // 第二个参数默认为 password 字段的值
            ]
        ]
    ];

    /**
     * 测试方法 1 - 测试当前字段的格式是否满足要求
     * 
     * 用法:
     * - 'id' => 'is_custom_string'
     * - 'id' => 'cus_str'
     *
     * @param string $data
     * @return bool
     */
    public static function is_custom_string($data)
    {
        return preg_match('/^[\w\d -]{8,32}$/', $data) ? true : false;
    }

    /**
     * 测试方法 2 - 测试当前字段是否存在于列表内
     * 
     * 用法:
     * - 'sequence' => 'is_in_custom_list[1st, First, 2nd, Second]'
     * - 'sequence' => '<custom>[1st, First, 2nd, Second]'
     * 
     * 这是一个第二个参数为可变长度参数的例子。如果不设置可变长度参数,那么它的写法如下,注意第二个参数必须是合法的 JSON Encoded 字符串。例如:
     * - 'sequence' => 'is_in_custom_list[["1st", "First", "2nd", "Second"]]'
     * - 'sequence' => '<custom>[["1st", "First", "2nd", "Second"]]'
     *
     * @param mixed $data
     * @param array $list
     * @return bool
     */
    public static function is_in_custom_list($data, $list)
    {
        return in_array($data, $list);
    }

    /**
     * 测试方法 3 - 验证当前字段是否与 password 字段相等
     * 
     * 用法:
     * - 'confirm_password' => 'is_equal_to_password'
     * - 'confirm_password' => '=pwd'
     * 
     * 这是一个默认参数的例子。用 `euqal` 方法来写效果也一样, 它相当于给 equal 方法加了默认参数 '@password'。例如:
     * - 'confirm_password' => `equal[@password]`,
     * - 'confirm_password' => `=[@password]`,
     *
     * @param string $data
     * @param string $password
     * @return bool
     */
    public static function is_equal_to_password($data, $password)
    {
        return $data == $password;
    }
}

"age" => "

// 串联,身高单位是必须的,且必须是 cm 或者 m
"height_unit" => "]" => [
    // 若身高单位是厘米 cm, 则身高必须大于等于100,小于等于200 
    "以替换成 [or]
"height" => [
    "[||]" => [
        // 若身高单位是厘米 cm, 则身高必须大于等于100,小于等于200 
        "

$rule = [
    "id" => " 时,name 只能是数字且长度必须大于 2
    // 当 id 大于等于 5 时,name 可以是任何字符串且长度必须大于 2
    "name" => "/^\d+$/:when(<(@id,5))|length>[2]",
    // 当 id 不小于 5 时,age 必须小于等于 18
    // 当 id 小于 5 时,age 可以是任何数字
    "age" => "int|<=[18]:when_not(<(@id,5))",
];

$rule = [
    // 特征是必要的,且只能是 height(身高) 或 weight(体重)
    "attribute" => "则不继续验证后续规则,即 centimeter 为任何值都可以。
    "centimeter" => "if(=(@attribute,height)){

$rule = [
    // 特征是必要的,且只能是 height(身高) 或 weight(体重)
    "attribute" => "则不继续验证后续规则,即 centimeter 为任何值都可以。
    "centimeter" => "if ( !=(@attribute,weight) ) { 

$rule = [
    "id" => "(@id,49)|<=(@id,51)) {
        if (!!=(@id,50)) {
            e if (!(!=(@id,52)) || =(@id,53)) {
        

$data = [
    "id" => 1,
    "name" => "Johnny",
    "favourite_fruit" => [
        "name" => "apple",
        "color" => "red",
        "shape" => "circular"
    ]
];

// 若要验证上述 $data,规则可以这么写
$rule = [
    "id" => "

$data = [
    "id" => 1,
    "name" => "Johnny",
    "favourite_color" => [
        "white",
        "red"
    ],
    "favourite_fruits" => [
        [
            "name" => "apple",
            "color" => "red",
            "shape" => "circular"
        ],
        [
            "name" => "banana",
            "color" => "yellow",
            "shape" => "long strip"
        ],
    ]
];

// 若要验证上述 $data,规则可以这么写
$rule = [
    "id" => "> [
            "name" => "

$rule = [
    "id" => "d|length>[3]",
    "favourite_color" => [
        // 表示 favourite_color 是可以为空的,如果不为空,要求其字段有且只有包含 0, 1,也就是只有两个子数据。
        "__self__" => "optional|optional|

$rule = [
    // 1. 叶子字段,直接使用 optional 方法,表示该字段是可选的
    "name" => "optional|string",
    // 2. 任意字段,在字段名后面添加 [optional],表示该字段是可选的
    "favourite_fruit[optional]" => [
        "name" => "          "taste" => "

$config = [
    'language' => 'en-us',                                      // Language, Default en-us
    'lang_path' => '',                                          // Customer Language file path
    'enable_entity' => false,                                   // Pre-parse ruleset into ruleset entity to reuse the ruleset without re-parse
    'validation_global' => true,                                // 1. true - validate all rules even though previous rule had been failed; 2. false - stop validating when any rule is failed
    'auto_field' => "data",                                     // If root data is string or numberic array, add the auto_field as the root data field name
    'reg_msg' => '/ >> (.*)$/sm',                               // Set the error message format for all the methods after a rule string
    'reg_preg' => '/^(\/.+\/.*)$/',                             // If a rule match reg_preg, indicates it's a regular expression instead of method
    'reg_preg_strict' => '/^(\/.+\/[imsxADSUXJun]*)$/',         // Verify if a regular expression is valid
    'symbol_if' => 'if',                                        // The start of IF construct. e.g. `if ( expr ) { statement }`
    'symbol_else' => 'else',                                    // The else part of IF construct. e.g. `else { statement }`. Then the elseif part is `else if ( expr ) { statement }`
    'symbol_logical_operator_not' => '!',                       // The logical operator not. e.g. `if ( !expr ) { statement }`
    'symbol_logical_operator_or' => '||',                       // The logical operator or. e.g. `if ( expr || expr ) { statement }`
    'symbol_rule_separator' => '|',                             // Serial rules seqarator to split a rule into multiple methods
    'symbol_parallel_rule' => '[||]',                           // Symbol of the parallel rule, Same as "[or]"
    'symbol_method_standard' => '/^([^\\(]*)\\((.*)\\)$/',      // Standard method format, e.g. equal(@this,1)
    'symbol_method_omit_this' => '/^([^\\[]*)\\[(.*)\\]$/',     // @this omitted method format, will add a @this parameter at first. e.g. equal[1]
    'symbol_parameter_separator' => ',',                        // Parameters separator to split the parameter string of a method into multiple parameters, e.g. equal(@this,1)
    'symbol_field_name_separator' => '.',                       // Field name separator of error message, e.g. "fruit.apple"
    'symbol_

$custom_config = [
    'reg_preg' => '/^Reg:(\/.+\/.*)$/',                         // If a rule match reg_preg, indicates it's a regular expression instead of method
    'symbol_rule_separator' => '&&',                            // Serial rules seqarator to split a rule into multiple methods
    'symbol_method_standard' => '/^(.*)#(.*)$/',                // Standard method format, e.g. equal(@this,1)
    'symbol_method_omit_this' => '/^(.*)~(.*)$/',               // @this omitted method format, will add a @this parameter at first. e.g. equal[1]
    'symbol_parameter_separator' => '+',                        // Parameters separator to split the parameter string of a method into multiple parameters, e.g. equal(@this,1)
    'symbol_field_name_separator' => '->',                      // Field name separator of error message, e.g. "fruit.apple"
    'symbol_

$rule = [
    "id" => "!*&&Reg:/^\d+$/",          // 必要的,且只能是数字
    "name" => "!*&&length><=~3+32",        // 必要的,且字符串长度必须大于3,小于等于32
    "favorite_animation" => [
        "name" => "!*&&length><=~1+64",                // 必要的,且字符串长度必须大于1,小于等于64
        "release_date" => "o?&&length><=#@this+4+64",  // 可选的,如果不为空,那么字符串长度必须大于4,小于等于64
    ]
];

// 在实例化类的时候加入配置
$validation_conf = [
    'language' => 'zh-cn',
];
$validation = new Validation($validation_conf);

// 或者调用接口
$validation->set_language('zh-cn'); // 将加载 ZhCn.php 国际化文件



class MyLang
{
    public $error_templates = [
        // 覆盖默认方法 = 的错误信息模板
        '=' => '@this must be equal to @p1(From MyLang)',
        // 新增方法 check_custom 的错误信息模板
        'check_custom' => '@this check_custom error!'
    ];
}

$validation->set_config(['lang_path' => '/MyPath/'])->set_language('MyLang');

// 必须是对象
$MyLang = (object)[];
$MyLang->error_templates = [
    // 覆盖默认方法 = 的错误信息模板
    '=' => '@this must be equal to @p1(From MyLang)',
    // 新增方法 check_custom 的错误信息模板
    'check_custom' => '@this check_custom error!'
];

$validation->custom_language($MyLang, 'MyLang');

// 在实例化类的时候加入配置
$validation_conf = [
    'validation_global' => false,
];
$validation = new Validation($validation_conf);

// 或者调用 set_validation_global 接口
$validation->set_validation_global(false);

// d" => '

"id" => '

"id" => "

$rule = [
    "id" => [
        '                    
            '@preg',
        ]
    ]
];

return false;

return "TAG:is_exclude_animal";

return "I don't like mouse";

return [
    "error_type" => "server_error",
    "message" => "I don't like snake",
    "extra" => "You scared me"
];

function check_animal($animal) {
    if ($animal == "") {
        return false;
    } else if ($animal == "mouse") {
        return "I don't like mouse";
    } else if ($animal == "snake") {
        return [
            "error_type" => "server_error",
            "message" => "I don't like snake",
            "extra" => "You scared me"
        ];
    } else if (!is_exclude_animals($animal)) {
        return "TAG:is_exclude_animal";
    } else if (is_fake_animals($animal)) {
        return [
            "error_type" => "server_error",
            "message" => "TAG:is_fake_animals"
        ];
    }

    return true;
}

$data = [
    "id" => 1,
    "name" => "GH",
    "age" => 18,
    "favorite_animation" => [
        "name" => "A Record of A Mortal's Journey to Immortality",
        "release_date" => "July 25, 2020 (China)",
        "series_directed_by" => [
            "",
            "Yuren Wang",
            "Zhao Xia"
        ],
        "series_cast" => [
            [
                "actor" => "Wenqing Qian",
                "character" => "Han Li",
            ],
            [
                "actor" => "ShiMeng-Li",
                "character" => "Nan Gong Wan",
            ],
        ]
    ]
];

// $data - 上述待验证的数据 
function validate($data) {
    // 设置验证规则
    $rule = [
        "id" => "       "favorite_animation" => [
            // favorite_animation.name 是必要的,且字符串长度必须大于1,小于等于64
            "name" => "         "series_directed_by" => [
                // favorite_animation.series_directed_by.* 每一个子元素必须满足其规则:不能为空且长度必须大于 3
                "*" => "|/^[A-Za-z ]+$/",
                    // favorite_animation.series_cast.*.character 不能为空且长度必须大于 3
                    "character" => ">get_result();
    } else {
        // 一共有四种错误信息格式可供选择。默认 Validation::ERROR_FORMAT_DOTTED_GENERAL
        return $validation->get_error();
    }
}

// 可以通过改变 get_error 的参数,找到适合自己的报错格式
// 例子中的 $data 基本都不满足 $rule ,可以改变 $data 的值,检测验证规则是否正确
echo json_encode(validate($data), JSON_PRETTY_PRINT + JSON_UNESCAPED_SLASHES + JSON_UNESCAPED_UNICODE) . "\n";

// 默认 Validation::ERROR_FORMAT_DOTTED_GENERAL
$validation->get_error();

$validation->get_error(Validation::ERROR_FORMAT_DOTTED_DETAILED);

$validation->get_error(Validation::ERROR_FORMAT_NESTED_GENERAL);

$validation->get_error(Validation::ERROR_FORMAT_NESTED_DETAILED);