mvlabs / ze-content-validation

Zend Expressive 的 PSR-7 验证中间件


README

Build Status

简介

Zend Expressive 内容验证是一个中间件,用于自动化验证传入的输入。

允许以下操作

  • 定义命名的输入过滤器。
  • 将命名的输入过滤器映射到路由。
  • 使用 Zend Problem Details 返回表示应用程序/问题的 PSR-7 响应,其中包含验证错误消息(在输入无效时)。

安装

运行以下 composer 命令

$ composer require mvlabs/ze-content-validation

配置

ze-content-validation 键是路由名称与值之间的映射,值是一个数组,它确定对于给定的请求应该响应哪个 HTTP 方法以及映射哪个输入过滤器。映射的键可以是 HTTP 方法或 * 通配符,用于应用于任何 HTTP 方法。

示例

'ze-content-validation' => [
    'user.add' => [
        'POST' =>  \App\InputFilter\UserInputFilter::class
    ],
],

在上面的示例中,\App\InputFilter\UserInputFilter 将被选中用于 POST 请求。

input_filter_spec

input_filter_spec 用于配置驱动的输入过滤器创建。此数组的键将是唯一的名称,但更常见的是基于它映射到 ze-content-validation 键下的服务名称。值将是一个输入过滤器配置数组,如 ZF2 手册中关于输入过滤器的部分所述。

示例

    'input_filter_specs' => [
        'App\\InputFilter\\LoginInputFilter' => [
            0 => [
                'name' => 'displayName',
                'required' => true,
                'filters' =>[],
                'validators' => [
                     0 => [
                        'name' => 'not_empty',
                     ]   
                ],
                
            ],
            1 => [
                'name' => 'password',
                'required' => true,
                'filters' => [],
                'validators' => [
                    0 => [
                        'name' => 'not_empty',
                    ],
                    1 => [
                        'name' => 'string_length',
                        'options' => [
                            'min' => 8, 
                            'max' => 12
                        ],
                    ],
                ],                
            ],
        ],
    ],

验证

在以下请求中,提供了一个格式无效的电子邮件值,并且完全省略了 displayName 字段。

POST /users HTTP/1.1
Accept: application/json
Content-Type: application/json; charset=utf-8

{
    "email": "foo",
    "password": "mySecretPassword!"
    
}

响应

HTTP/1.1 422 Unprocessable Entity
Content-Type: application/problem+json

{
  "detail": "Validation Failed",
  "status": 422,
  "title": "Unprocessable Entity",
  "type": "https://httpstatus.es/422",
  "errors": {
    "email": {
        "emailAddressInvalidFormat": "The input is not a valid email address. Use the basic format local-part@hostname"
    },
    "displayName": {
      "isEmpty": "Value is required and can't be empty"
    }    
  },
}