# Validate Data

> 依据 JSON Schema（Draft-07）校验输入载荷。

Source: https://docs.sommatic.ai/zh/nodes/data.validate/

- 标识: `data.validate`
- 类别: 数据
- 版本: 1.0.0
- 状态: 可用
- 执行方式: sync

依据 JSON Schema（Draft-07）校验输入载荷。

在工作流继续执行之前，严格校验结构、类型和约束，以保障数据质量和完整性。校验失败时，执行会被路由到“invalid”端口，并附带详细的错误元数据。

**功能特性：**
- 底层使用 AJV（Another JSON Validator）。
- 支持完整的 JSON Schema 规范。
- 在元数据中提供详细的错误报告。

**适用场景：**
- 校验 API 请求体。
- 在写入数据库前确保必填字段存在。
- 校验配置参数。

## 配置

- `schema` (object, 必填): 用于校验的 schema 对象。

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `valid` (默认): 数据符合 schema。
- `invalid`: 数据不符合 schema。
- `error`: Schema 编译错误或系统错误。

## 输入契约

- `payload` (object, 可选)

## 输出契约

- `payload` (object, 可选)

## 在表达式中

后续节点可通过 `$("Validate Data").item.json.<路径>` 读取此节点输出中的内容（请把 `Validate Data` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `valid` 返回的路径，依据“端口”一节所示的输出。

- `$("Validate Data").item.json.payload` (object) **worker 不返回：读取结果为 undefined.**
- `$("Validate Data").item.json.id` (string) = `"pay_88"` (编辑器不提示)
- `$("Validate Data").item.json.amount` (number) = `120.5` (编辑器不提示)


## 工作原理

使用 Ajv 8 按 JSON Schema 校验输入 payload，并将原样的 payload 路由到 `valid` 或 `invalid`。

1. 解析配置。`schema` 可以是对象或 JSON 字符串（代码编辑器保存的形式）；字符串会被解析。
2. schema 缺失或不是对象时失败。
3. 每次运行都用 Ajv 编译 schema（`allErrors: true`，启用严格模式，默认 draft-07）。
4. 有效：payload 从 `valid` 输出。
5. 无效：payload 从 `invalid` 输出，所有 Ajv 错误列在 `meta.validation_errors` 中。

## 在工作流中

### 节点

```json
{
  "node_id": "node-validate-payment",
  "label": "Validate payment",
  "operator_slug": "data.validate",
  "operator_version": "1.0.0",
  "config": {
    "schema": {
      "type": "object",
      "required": [
        "id",
        "amount"
      ],
      "properties": {
        "id": {
          "type": "string"
        },
        "amount": {
          "type": "number",
          "minimum": 0
        }
      }
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "id": "pay_88",
    "amount": 120.5
  },
  "port": "valid"
}
```

## 输出端口 (代码中的行为)

### `valid`

payload 符合 schema。

```json
{
  "id": "pay_88",
  "amount": 120.5
}
```

### `invalid`

payload 违反 schema。`data` 为原样的 payload。

```json
{
  "id": "pay_88",
  "amount": "120.5"
}
```

### `error`

schema 缺失、不是有效 JSON 或无法编译。

```json
{
  "ok": false,
  "errors": [
    "Validation Error: strict mode: unknown keyword: \"required_fields\""
  ],
  "port": "error"
}
```

## 代码中的行为

- `schema`: schema 中包含 `{{ }}` 的字符串值会在编译前由 Expression Engine 解析。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Schema is not valid JSON: <message>` | `error` | `schema` 是字符串，但不是有效的 JSON。 |
| `Schema definition is required and must be an object` | `error` | `schema` 缺失或解析结果不是对象。 |
| `Validation Error: strict mode: unknown keyword: "<keyword>"` | `error` | schema 使用了 Ajv 不认识的关键字。严格模式会在编译时拒绝。 |
| `Validation Error: unknown format "<format>" ignored in schema at path "<path>"` | `error` | `format`（`email`、`date-time`、`uri` 等）需要 ajv-formats，但它未加载，因此任何 `format` 都会导致编译失败。请改用 `pattern`。 |

## 说明与限制

- `meta` 只记录在运行步骤中：下游节点收到的 payload 是 `data`，无法通过 `$json` 或 `$("Node")` 读取 `meta`。
- `invalid` 不是错误：信封中 `ok: true`。请将 `invalid` 连接到处理被拒数据的分支。
- 当返回的信封没有 `data`（或 `data` 为假值）时，引擎会把整个信封作为节点输出：经 `error` 端口时，下一个节点收到的 payload 是 `{ ok: false, errors: [...], port: "error" }`。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "data.validate",
  "name": "Validate Data",
  "category": "data",
  "version": "1.0.0",
  "description": "Validates the input payload against a JSON Schema (Draft-07).\n\n  Ensures data quality and integrity by strictly enforcing structure, types, and constraints before proceeding in the workflow. If validation fails, execution is routed to the 'invalid' port with detailed error metadata.\n\n  **Features:**\n  - Uses AJV (Another JSON Validator) under the hood.\n  - Supports full JSON Schema specification.\n  - Provides detailed error reports in the metadata.\n\n  **Use Cases:**\n  - Verifying API request bodies.\n  - Ensuring mandatory fields exist before database insertion.\n  - Validating configuration parameters.",
  "capabilities": [
    "validation",
    "schema",
    "json",
    "quality"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "schema"
    ],
    "properties": {
      "schema": {
        "type": "object",
        "title": "JSON Schema",
        "description": "The schema object to validate against.",
        "ui_widget": "code_editor",
        "ui_options": {
          "language": "json"
        }
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "description": "The payload to validate.",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "description": "The original payload (if valid).",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "valid",
      "label": "Valid",
      "is_default": true,
      "description": "Data conforms to schema."
    },
    {
      "port_id": "invalid",
      "label": "Invalid",
      "description": "Data violates matches schema."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Schema compilation or system error."
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "validation",
    "quality",
    "schema"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_link_loom",
    "profile": {
      "name": "Link Loom",
      "verified": true,
      "url": "https://me.veripass.com/link-loom",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "required": [
    "schema"
  ],
  "properties": {
    "schema": {
      "type": "object",
      "title": "JSON Schema",
      "description": "The schema object to validate against.",
      "ui_widget": "code_editor",
      "ui_options": {
        "language": "json"
      }
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "description": "The payload to validate.",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "description": "The original payload (if valid).",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "valid",
    "label": "Valid",
    "is_default": true,
    "description": "Data conforms to schema."
  },
  {
    "port_id": "invalid",
    "label": "Invalid",
    "description": "Data violates matches schema."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Schema compilation or system error."
  }
]
```
