pedrohenriques / data-validator
易于使用且高度可定制的PHP数据验证器。
Requires
- php: >=5.4
This package is not auto-updated.
Last update: 2024-09-14 19:31:13 UTC
README
这是一个PHP库,它允许以简单和可定制的的方式进行数据验证。
代码将遍历数据数组,并对每个项目执行指定的验证。最后,任何失败的验证都将生成一个错误消息,您可以显示它。
所有验证和错误消息都可以自定义,甚至默认消息,您还可以非常容易地“即时”创建新的验证。
说明
设置
=> Composer
将以下内容添加到项目的 composer.json 文件中
{
"require": {
"pedrohenriques/data-validator": "1.*"
}
}
将版本替换为您喜欢的版本。
=> 手动
- 将
src文件夹复制到您的项目中。 - 在您希望使用数据验证器的网页上引用
DataValidator.php文件,例如,使用require_once("path/to/DataValidator.php")。
### 使用数据验证器
为了使用数据验证器,请使用以下代码创建 DataValidator 类的实例
use DataValidator\DataValidator;
$validator = new DataValidator([string $json_path]);
使用
- $json_path: 包含默认错误消息的每个验证类型的字符串路径。该文件包含
error_msg.json文件的路径。该文件包含每个验证类型的默认错误消息。
如果没有提供路径,代码将假设该文件位于src/data/error_msg.json。
一旦类实例化,代码 `$validator->validate(array $data, array $validations[, $single_fail]);` 将执行验证并生成任何错误消息。
使用
- $data: 包含要验证的数据的数组。
- $validations: 包含对每个 $data 条目的期望验证的数组(下面提供语法)。
- $single_fail: 控制是否应该执行一个 $data 条目的所有验证,或者是否在失败一个时停止。
True将在第一个失败时停止 $data 条目的验证,而False将无论失败多少个都执行一个 $data 条目的所有验证。
默认情况下,代码将假设值为False。
#### => `$validations` 参数语法
完整的语法是 $validations = ["field;alias" => ["check_type1;value1;value2...", "check_type2;value1;value2...", ...], ...] 其中
- field: 要使用的 $data 条目的名称。名称必须在 $data 和 $validations 数组中匹配。
- alias: [可选] 字段的别名。
如果提供,则将使用别名而不是字段名称在错误消息中使用。
如果没有提供,则将使用字段名称在错误消息中使用。 - check_type: 问题的验证名称。
- value: 将提供给验证代码和错误消息的一个值。
如果所需的值是 $data 条目之一,请使用格式%field%,它将被替换为该字段的数据条目。
#### => 默认验证
此存储库附带以下可用的验证
#### => 示例
给定以下输入
$data = [
"user_name" => "Pedro Henriques",
"email" => "pedro@pedrojhenriques.com",
"password" => "pw123",
"password_conf" => "pw456",
"gender" => "male",
"commission" => "200",
"planet" => "Mars"
];
以及以下验证
$validations = [
"user_name;User Name" => ["required", "max_len;50"],
"email;Email" => ["required", "email"],
"password;Password" => ["required", "min_len;6", "max_len;50"],
"password_conf;Password Confirmation" => ["match;%password%"],
"gender;Gender" => ["in;male;female"],
"commission;Commission" => ["required", "range;0;100"],
"planet;Planet of Origin" => ["required", "match;Earth"],
];
将生成以下错误
Array
(
[password] => Array
(
[0] => The length of the Password provided is too short.
)
[password_conf] => Array
(
[0] => The Password Confirmation provided doesn't match Password.
)
[commission] => Array
(
[0] => The value provided for the Commission field must be between 0 and 100.
)
[planet] => Array
(
[0] => The Planet of Origin provided doesn't match Earth.
)
)
#### => 可用方法
假设 $validator 包含 DataValidator 类的实例。
以下方法允许执行验证并访问其结果
=> **基本方法**
=> **高级方法**
注意:这些方法用于自定义数据验证器。有关更多详细信息,请参阅下面的 自定义数据验证器 主题。
## 自定义数据验证器
您可以通过两种方式自定义验证以及错误消息
- 持久性:将新的验证作为
类添加,并将错误信息作为error_msg.json文件中的一个条目。 - 临时性:将新的验证注册为临时
函数,并将错误信息作为临时字符串。
### 验证
当调用验证时,代码将首先寻找具有相同检查类型的临时函数。如果没有找到匹配的函数,代码将寻找具有匹配名称的已定义类(下面将说明命名约定)。
这意味着自定义临时验证将优先于持久性验证。如果您想更改持久性验证的行为,请注册一个具有相同检查类型的临时函数。
- **类**:关于持久性验证,以类形式存在,代码期望类名遵循以下命名约定:`ValCheckType`。所有类名均以`Val`开头,后跟驼峰式样检查类型。在检查类型中,下划线将被视为单词分隔符。
These classes should implement the interface `iValidation`, located at `src/interfaces/interfaces.php`.
**NOTE:** The code expects a validation class to belong in the **DataValidator\Validations** namespace.
As an example:
```
namespace DataValidator\Validations;
use DataValidator\Interfaces\iValidation;
class ValMyClass implements iValidation {
public function runCheck($field, $input, array $params) {
// validation code goes here!
// return True if the validation passed or False if it failed.
}
}
```
The code will automatically look for, and include, a file with the same name as the validation class in the directory `src/validations`.
However, as long as the classes are defined by the time the code calls them, they don't need to be in a file with the same name, or in the default directory.
**EX:**
For a check type called `min_len` the code expects a class named `ValMinLen` and will automatically look for and include a file named `ValMinLen.php`.
For a check type called `required` the code expects a class named `ValRequired` and will look for a file named `ValRequired.php`.
- **函数**:关于临时验证,以函数形式存在,必须在注册到数据验证器之前才能使用。要注册验证函数,请使用前面列出的高级方法`addValidation`。
The `$check_type` parameter must exactly match the check type provided in the `$validations` array of the `DataValidator` class' constructor.
The `$function` parameter must be a function that returns `True` if the check passed or `False` if it failed.
The function will be given the same parameters as the `runCheck()` method of the `iValidation` interface, located at `src/interfaces/interfaces.php`, so in order to have access to that information inside this function those parameters must be defined in the function's declaration.
The function can be lambda/anonymous or "named".
**EX:**
The following code will register a new temporary validation, accessible as check type `custom_val`:
```
$validator->addValidation("custom_val", function($field, $input, array $params) {
// validation code goes here!
// return True if the validation passed or False if it failed.
});
```
- **验证可用信息**:当执行验证时,无论是通过调用验证类的`runCheck`方法还是运行临时`$function`,都会向它们提供以下参数
- `$field`: String with the name of the $data entry being validated.<br><br>
- `$input`: String with the value of the $data entry being validated. If `$field` doesn't exist in `$data`, then `$input` will be `null`.<br><br>
- `$params`: Array with all validation values provided in the `$validations` array (zero-based indexed).
**示例**:
给定以下代码
$data = [
"commission" => "20",
"tax" => "25"
];
$validations = [
"commission;Commission Perc." => ["custom_val;10;100;47"],
"tax;Tax Perc." => ["match;%commission%"]
];
验证方法/函数可用的信息
- 对于
$data["commission"]和检查类型custom_val
$field:"commission"$input:"20"$params:[0 => "0", 1 => "100", 2 => "47"]
- 对于
$data["tax"]和检查类型`match`- `$field`: `"tax"`
- `$input`: `"25"`
- `$params`: `[0 => "20"]` -- 这里`%commission%`被佣金输入替换
### 错误信息
当生成错误信息时,代码将首先寻找具有相同检查类型和字段的临时字符串。如果没有找到匹配的字符串,代码将寻找具有匹配名称的持久性消息。
这意味着自定义临时字符串将优先于持久性消息。如果您想更改持久性消息的内容,请注册一个具有相同检查类型的临时字符串。
- **"error_msg.json"**:关于持久性消息,必须将它们存储在默认位于`src/data/error_msg.json`的`error_msg.json`中。键应与`$validations`中提供的检查类型完全匹配,值应为相应的错误消息。
- **临时字符串**:关于临时消息,必须在注册到数据验证器之前才能使用。要注册临时消息,请使用前面列出的高级方法`addMessage`。
The `$check_type` parameter must exactly match the check type provided in the `$validations` array of the `DataValidator` class' constructor.
- **动态错误信息的可用信息**:以下特殊关键字可以在错误信息字符串中使用,以实现动态消息
- `%field%`: Will be replaced by the name of the field were the error occurred.
Will use the field's alias, if one was provided.<br><br>
- `%check_type%`: Will be replaced by the check type were the error occurred.<br><br>
- `%input%`: Will be replaced by the $data value being validated that generated the error.<br><br>
- `%params[key]%`: Will be replaced by the actual validation value in use with the given "key"<br><br>
- `%%key%%`: Will be replaced by the value in $validations with the given "key"
If the value was another field, it's alias will be used, if one was provided.<br><br>
**NOTE:** If "key" is `...`, then all available values for the failed validation will be displayed, separated by `, `
**示例**:
给定以下代码
$data = [
"commission" => "20",
"tax" => "25"
];
$validations = [
"commission;Commission Perc." => ["custom_val;10;100;47"],
"tax;Tax Perc." => ["match;%commission%"]
];
错误信息可用的信息
- 对于
$data["commission"]和检查类型custom_val
%field%:佣金百分比%check_type%:custom_val%input%:20%params[0]%:10%params[1]%:100%params[2]%:47%params[...]%:10, 100, 47%%0%%:10%%1%%:100%%2%%:47%%...%%:10, 100, 47
- 对于
$data["tax"]和检查类型`match`- `
%field%`: `tax`- `
%check_type%`: `match`- `
%input%`: `25`- `
%params[0]%`: `20`- `
%params[...]%`: `20`- `
%%0%%`: `佣金百分比`- `
%%...%%`: `佣金百分比`### 短路规则
可以配置某些检查类型和输入值的组合,这些组合将“短路”其余验证,防止它们执行。
要注册临时短路规则,请使用前面列出的高级方法`addShortCircuit`。
永久性短路组合在$short_circuit_rules变量中定义,该变量位于DataValidator类定义的开始处。
默认情况下,此变量的值为以下内容
$short_circuit_rules = [
["check" => "required", "input" => [null, ""], "run_check" => true],
["check" => "!required", "input" => [null, ""], "run_check" => false]
];
第一个条目如下所示:"如果正在验证的字段有required检查,并且$data条目为null或"",则执行required检查,但不执行其他检查。"
这可以防止生成多个错误消息,以及执行不必要的检查,因为没有输入值进行验证,但需要输入值。
请注意,尽管执行了将失败的required检查,但仍会为该检查生成错误消息。
第二个条目如下所示:"如果正在验证的字段没有required检查,并且$data条目为null或"",则不执行required检查或其他任何检查。"
这可以防止未填写(留空)的可选字段被验证,从而可能生成错误消息,而实际上不需要验证。
然而,如果提供了该字段($input将是一个非空字符串),则将执行任何相关的检查。
请注意,使用!表示检查不存在。