You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为express-json-validator-middleware生成动态JSON校验错误信息?

解决express-json-validator-middleware数组字段重复错误消息的方案

不用手动为每个类似colors的数组字段重复编写错误消息,你可以通过封装可复用的schema生成函数+模板化错误消息的方式,批量生成精准的校验规则和错误提示,同时保留自定义扩展的灵活性。

1. 封装通用字符串数组校验函数

创建一个工具函数,接收字段名称、校验参数(如最小/最大长度、是否去重),自动生成带精准错误消息的schema:

// 工具函数:生成字符串数组校验规则
const createStringArraySchema = (fieldName, options = {}) => {
  // 默认参数
  const {
    minItems = 1,
    maxItems = 6,
    uniqueItems = true,
    // 支持自定义错误消息覆盖默认模板
    customErrorMessages = {}
  } = options;

  // 自动生成精准错误消息
  const defaultErrorMessages = {
    type: `${fieldName} 必须是数组`,
    minItems: `${fieldName} 至少包含 ${minItems} 项`,
    maxItems: `${fieldName} 最多包含 ${maxItems} 项`,
    uniqueItems: `${fieldName} 不能包含重复项`,
    "items.type": `${fieldName} 中的每一项必须是字符串`
  };

  return {
    type: "array",
    items: { type: "string" },
    minItems,
    maxItems,
    uniqueItems,
    errorMessage: { ...defaultErrorMessages, ...customErrorMessages }
  };
};

2. 批量生成字段校验规则

使用时只需传入字段名和自定义参数,无需重复编写错误消息:

// 构建完整的请求体校验schema
const requestSchema = {
  body: {
    type: "object",
    properties: {
      // 基础用法:使用默认参数
      colors: createStringArraySchema("颜色"),
      // 自定义参数:修改最大长度
      tags: createStringArraySchema("标签", { maxItems: 10 }),
      // 自定义参数+覆盖错误消息
      categories: createStringArraySchema("分类", {
        minItems: 2,
        uniqueItems: false,
        customErrorMessages: {
          minItems: "分类至少要选2个哦"
        }
      })
    },
    required: ["colors"]
  }
};

3. 进阶:抽离错误消息模板(可选)

如果需要统一维护所有错误消息的格式,可以把模板抽成单独的配置文件,便于全局修改:

// errorTemplates.js - 全局错误消息模板
export const arrayErrorTemplates = {
  type: "{field} 必须是数组类型",
  minItems: "{field} 至少需要 {count} 个元素",
  maxItems: "{field} 最多只能有 {count} 个元素",
  uniqueItems: "{field} 不允许出现重复内容",
  itemsString: "{field} 的每个元素都必须是字符串"
};

然后在工具函数中替换占位符:

import { arrayErrorTemplates } from "./errorTemplates.js";

const createStringArraySchema = (fieldName, options = {}) => {
  const { minItems = 1, maxItems = 6, uniqueItems = true, customErrorMessages = {} } = options;

  const errorMessage = {
    type: arrayErrorTemplates.type.replace("{field}", fieldName),
    minItems: arrayErrorTemplates.minItems.replace("{field}", fieldName).replace("{count}", minItems),
    maxItems: arrayErrorTemplates.maxItems.replace("{field}", fieldName).replace("{count}", maxItems),
    uniqueItems: arrayErrorTemplates.uniqueItems.replace("{field}", fieldName),
    "items.type": arrayErrorTemplates.itemsString.replace("{field}", fieldName),
    ...customErrorMessages
  };

  return {
    type: "array",
    items: { type: "string" },
    minItems,
    maxItems,
    uniqueItems,
    errorMessage
  };
};

这种方式既减少了重复代码,又能保证每个字段的错误提示精准清晰,同时支持针对特殊字段自定义错误消息,兼顾复用性和灵活性。

内容的提问来源于stack exchange,提问作者Kisan Kumavat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 17:11:17