cmanley / validate
PHP 验证库。您可以使用它验证几乎任何内容,例如表单提交、函数参数等。
0.9.9
2024-02-27 18:47 UTC
Requires
- php: >=7.1
README
PHP 验证库。受 Perl 的 Params::Validate 启发。您可以使用它验证几乎任何内容,但通常它可用于(严格地)验证 HTML 表单、读取 CSV 文件时字段、函数参数等。
需求
- PHP 7.1 或更高版本
安装
下载或从 git 检出,或安装 Packagist 包 cmanley/validate。
警告:这仍然是一个处于早期阶段的工作,API 可能随时更改。因此,请使用固定版本,除非您准备好自己解决问题,否则不要从 master 分支下载。
概要
函数关联数组参数验证示例
<?php require_once('/path/to/Validate/Validator.php'); # or use composer autoloader function save_student_score(array $params) { # Create the validator object. By using static, it is only created once and persists for all function calls. $validator = new \Validate\Validator([ 'trim' => true, # trim all string values 'null_empty_strings' => true, # convert empty string values to null 'specs' => [ 'name' => [ 'type' => 'string', 'mb_max_length' => 2, 'mb_max_length' => 30, ], 'birthdate' => [ 'type' => 'string', 'regex' => '#^[0-3]\d/[01]\d/\d{4}$#', # expect dd/mm/yyyy 'after' => function(&$value) { # want yyyy-mm-dd if (is_string($value) && preg_match('#^(\d{2})/(\d{2})/(\d{4})$#', $value, $matches)) { $value = $matches[3] . '-' . $matches[2] . '-' . $matches[1]; } }, 'optional' => true, ], 'score' => [ 'types' => ['float', 'integer'], 'max_value' => 10, 'min_value' => 0, ], ], ]); # Actually validate the parameters. This will throw an exception in invalid parameters are found. $params = $validator->validate($params); # Insert $params into database here. } $error = null; try { save_student_score($_POST); } catch (\Validate\Exception\ValidationException $e) { $error = $e->getMessage(); } if ($error) { # display error message. } else { # display success message. }
请参阅 Wiki 中的 API 文档。
许可
本库中所有代码均根据 LICENSE 文件中的 MIT 许可证授权