arfeen / json-schema-validator
此软件包最新版本(1.0.0)没有提供许可证信息。
根据数据类型和约束使用预定义模式验证JSON。
1.0.0
2018-03-15 12:43 UTC
Requires
- php: ^5.3.0 || ^7.0
This package is not auto-updated.
Last update: 2024-09-21 10:27:34 UTC
README
此类通过使用基于基本必要数据类型的预定义模式来验证JSON有效负载。可以通过创建新类来扩展数据类型验证,可以通过在Constraints类中编写新函数来添加新的约束。
此模式验证器适用于以下类型
- 文本
- 数值
- 日期
- 数组
- 布尔值
- 选择
约束
-
max_length(字符串长度)
-
required(对于必填字段)
-
value_range min_value max_value(对于数值字段)
-
choices [choices array](对于预定义的选择)
-
min_item_count
-
max_item_count(对于数组数据类型,限制项目数量)
-
sub_nodes(对于嵌套对象)
示例模式
$_payLoadSchema = [
[
'node' => [
'name' => 'title',
'type' => 'text',
'required' => true,
'max_length' => 20
]
],
[
'node' => [
'name' => 'action',
'type' => 'text',
'required' => true,
'max_length' => 20,
'choices' => [
"CUSTOMER_DATA",
"CUSTOMER_CREATE"
]
]
],
[
'node' => [
'name' => 'transaction_amount',
'type' => 'numeric',
'required' => true,
'value_range' => [
'min_value' => 10,
'max_value' => 100
]
]
],
[
'node' => [
'name' => 'transaction_date',
'type' => 'choices',
'required' => true,
'choices' => [
"2018-01-01",
"2018-01-02"
]
]
],
[
'node' => [
'name' => 'customer_ids',
'type' => 'array',
'required' => true,
'max_item_count' => 2
]
],
[
'node' => [
'name' => 'is_active',
'type' => 'boolean',
'required' => false
]
],
[
'node' => [
'name' => 'additional_data',
'type' => 'object',
'sub_nodes' => [
['node' => [
'name' => 'additional_field_1',
'type' => 'text',
'max_length' => "100"
]],
['node' => [
'name' => 'additional_field_2',
'type' => 'numeric'
]]
]
]
]
];
验证的JSON有效负载示例
$json_raw = '
{
"title": "This is titlle",
"action": "CUSTOMER_CREATE",
"transaction_amount": "44",
"transaction_date": "2018-01-01",
"customer_ids": [
1001,
1002,
1003
],
"is_active": true,
"additional_data": {
"additional_field_2": 10
}
}
';
用法
<?php
$jsonschemavalidator = new JsonSchemaValidator();
$jsonschemavalidator->validateSchema($_payLoadSchema, $json_raw);
if($validated){
echo "JSON Validated";
} else {
echo "JSON not validated";
print_r($jsonschemavalidator->getErrors());
}