wixel / gump
一个快速、可扩展且独立的PHP输入验证类,允许您验证任何数据。
v2.1.0
2024-04-29 14:43 UTC
Requires
- php: >=7.1
- ext-bcmath: *
- ext-iconv: *
- ext-intl: *
- ext-json: *
- ext-mbstring: *
Requires (Dev)
- kamermans/docblock-reflection: ^1.0
- maddhatter/markdown-table: ^1.0
- mockery/mockery: ^1.3
- php-coveralls/php-coveralls: ^2.5
- phpspec/prophecy: ^v1.10|^v1.17
- phpunit/phpunit: ^6|^9
This package is not auto-updated.
Last update: 2024-09-16 16:35:40 UTC
README
GUMP是一个独立的PHP数据验证和过滤类,它使验证任何数据变得简单而痛苦,无需依赖框架。GUMP自2013年以来一直是开源的。
支持广泛的PHP版本(从php7.1到php8.3)和零依赖!
使用composer安装
composer require wixel/gump
验证的短格式示例
$is_valid = GUMP::is_valid(array_merge($_POST, $_FILES), [ 'username' => 'required|alpha_numeric', 'password' => 'required|between_len,4;100', 'avatar' => 'required_file|extension,png;jpg', 'tags' => 'required|alpha_numeric', // ['value1', 'value3'] 'person.name' => 'required', // ['person' => ['name' => 'value']] 'persons.*.age' => 'required' // ['persons' => [ // ['name' => 'value1', 'age' => 20], // ['name' => 'value2'] // ]] ]); // 1st array is rules definition, 2nd is field-rule specific error messages (optional) $is_valid = GUMP::is_valid(array_merge($_POST, $_FILES), [ 'username' => ['required', 'alpha_numeric'], 'password' => ['required', 'between_len' => [6, 100]], 'avatar' => ['required_file', 'extension' => ['png', 'jpg']] ], [ 'username' => ['required' => 'Fill the Username field please.'], 'password' => ['between_len' => '{field} must be between {param[0]} and {param[1]} characters.'], 'avatar' => ['extension' => 'Valid extensions for avatar are: {param}'] // "png, jpg" ]); if ($is_valid === true) { // continue } else { var_dump($is_valid); // array of error messages }
过滤的短格式示例
$filtered = GUMP::filter_input([ 'field' => ' text ', 'other_field' => 'Cool Title' ], [ 'field' => ['trim', 'upper_case'], 'other_field' => 'slug' ]); var_dump($filtered['field']); // result: "TEXT" var_dump($filtered['other_field']); // result: "cool-title"
长格式示例
$gump = new GUMP(); // set validation rules $gump->validation_rules([ 'username' => 'required|alpha_numeric|max_len,100|min_len,6', 'password' => 'required|max_len,100|min_len,6', 'email' => 'required|valid_email', 'gender' => 'required|exact_len,1|contains,m;f', 'credit_card' => 'required|valid_cc' ]); // set field-rule specific error messages $gump->set_fields_error_messages([ 'username' => ['required' => 'Fill the Username field please, its required.'], 'credit_card' => ['extension' => 'Please enter a valid credit card.'] ]); // set filter rules $gump->filter_rules([ 'username' => 'trim|sanitize_string', 'password' => 'trim', 'email' => 'trim|sanitize_email', 'gender' => 'trim', 'bio' => 'noise_words' ]); // on success: returns array with same input structure, but after filters have run // on error: returns false $valid_data = $gump->run($_POST); if ($gump->errors()) { var_dump($gump->get_readable_errors()); // ['Field <span class="gump-field">Somefield</span> is required.'] // or var_dump($gump->get_errors_array()); // ['field' => 'Field Somefield is required'] } else { var_dump($valid_data); }
⭐ 可用验证器
重要:如果您使用管道或分号作为参数值,您必须使用数组格式。
$is_valid = GUMP::is_valid(array_merge($_POST, $_FILES), [ 'field' => 'regex,/partOf;my|Regex/', // NO 'field' => ['regex' => '/partOf;my|Regex/'] // YES ]);
⭐ 可用过滤器
过滤器规则也可以是任何PHP原生函数(例如:trim)。
其他可用方法
/** * Setting up the language, see available languages in "lang" directory */ $gump = new GUMP('en'); /** * This is the most flexible validation "executer" because of it's return errors format. * * Returns bool true when no errors. * Returns array of errors with detailed info. which you can then use with your own helpers. * (field name, input value, rule that failed and it's parameters). */ $gump->validate(array $input, array $ruleset); /** * Filters input data according to the provided filterset * * Returns array with same input structure but after filters have been applied. */ $gump->filter(array $input, array $filterset); // Sanitizes data and converts strings to UTF-8 (if available), optionally according to the provided field whitelist $gump->sanitize(array $input, $whitelist = null); // Override field names in error messages GUMP::set_field_name('str', 'Street'); GUMP::set_field_names([ 'str' => 'Street', 'zip' => 'ZIP Code' ]); // Set custom error messages for rules. GUMP::set_error_message('required', '{field} is required.'); GUMP::set_error_messages([ 'required' => '{field} is required.', 'valid_email' => '{field} must be a valid email.' ]);
创建自己的验证器和过滤器
通过使用回调函数,添加自定义验证器和过滤器变得简单。
/** * You would call it like 'equals_string,someString' * * @param string $field Field name * @param array $input Whole input data * @param array $params Rule parameters. This is usually empty array by default if rule does not have parameters. * @param mixed $value Value. * In case of an array ['value1', 'value2'] would return one single value. * If you want to get the array itself use $input[$field]. * * @return bool true or false whether the validation was successful or not */ GUMP::add_validator("equals_string", function($field, array $input, array $params, $value) { return $value === $params; }, 'Field {field} does not equal to {param}.'); // You might want to check whether a validator exists first GUMP::has_validator($rule); /** * @param string $value Value * @param array $param Filter parameters (optional) * * @return mixed result of filtered value */ GUMP::add_filter("upper", function($value, array $params = []) { return strtoupper($value); }); // You might want to check whether a filter exists first GUMP::has_filter($rule);
或者,您可以简单地创建一个继承自GUMP的自己的类。您只需记住
- 对于过滤器方法,请将方法名以"filter_"开头。
- 对于验证器方法,请将方法名以"validate_"开头。
class MyClass extends GUMP { protected function filter_myfilter($value, array $params = []) { return strtoupper($value); } protected function validate_myvalidator($field, array $input, array $params = [], $value) { return $input[$field] === 'good_value'; } } $validator = new MyClass(); $validated = $validator->validate($_POST, $rules);
全局配置
此配置值允许您更改默认规则分隔符(例如:required|contains,value1;value2
更改为required|contains:value1,value2
)。
GUMP::$rules_delimiter = '|'; GUMP::$rules_parameters_delimiter = ','; GUMP::$rules_parameters_arrays_delimiter = ';';