func0der/ze-content-validation

PSR-7 验证中间件,适用于 Laminas Mezzio


README

CI-Test

简介

Mezzio Content Validation(原名 Zend Expressive Content Validation)是 Mezzio 中间件,用于自动化处理输入验证。

允许以下操作

  • 定义命名输入过滤器。
  • 将命名输入过滤器映射到路由。
  • 使用 Laminas Problem Details 返回 PSR-7 响应表示形式,包含无效输入时的验证错误消息

安装

运行以下 composer 命令

$ composer require func0der/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 键下映射的服务名称。值将是输入过滤器配置数组,如 Laminas 手册中输入过滤器部分所述。

示例

    '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"
    }    
  },
}