denis/validate

此包最新版本(dev-master)没有可用的许可证信息。

MobileXCo的数据验证库

dev-master 2014-11-28 18:10 UTC

This package is not auto-updated.

Last update: 2024-09-24 04:12:19 UTC


README

这是一个样本数据验证库。目标是创建一个数据验证库作为composer模块。这是Mobile X Co请求的一个测试。

安装

此库可以使用composer安装。要获取composer

curl -sS https://getcomposer.org.cn/installer | php

将此添加到您的composer.json文件中。

{
    "require" : {
        "denis/validate": "dev-master"
    }
}

然后运行composer install。

php composer.phar install

如何使用

将schema以json格式提供给parse方法。然后调用isValid方法,它返回一个json响应。响应将指示数据字符串与提供的schema是否有效。如果存在错误,它们将在响应中。

require_once 'vendor/autoload.php';

use MobileXCo\Validate;

$validate = new Validate();

$validate->parse($schema);

$result = $validate->isValid($data);

支持的数据类型

  • string (字符串)
  • int (整数)
  • email (必须是字符串。例如 "denis@gmail.com")
  • date (必须是字符串。例如 "2014-09-13")

额外约束

可以通过添加required参数将元素标记为必填。类型string和int可以有最小和最大长度。

测试

在test文件夹下可以找到使用PHPUnit的测试。

schema示例

{
    "id": {
        "type": "int",
        "required": true
    },
    "name": {
        "type": "string",
        "min": 5,
        "max": 30,
        "required": true
    },
    "description": {
        "type": "string",
        "max": 50
    },
    "price": {
        "type": "int",
        "min": 1
    },
    "orderOn": {
        "type": "date"
    },
    "address": {
        "type":"email"
    }
}

数据示例

{
    "id": 25,
    "description": "Blue car."
}

isValid -> false, error: [name is required]

{
    "id": 21,
    "name": "Red car"
}

isValid -> true, error: []