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

React中使用JSON Forms自定义错误消息失败求助

React + JSON Forms 自定义校验错误消息解决方案

问题分析

核心问题是JSON Forms默认的AJV校验器未正确集成ajv-errors插件,Schema中自定义错误消息的配置不符合要求,同时代码检查工具对未知关键字errorMessage报错。

解决步骤

1. 安装依赖

确保安装兼容版本的ajv和ajv-errors:

npm install ajv ajv-errors --save

2. 配置自定义AJV实例

创建集成ajv-errors的AJV实例,必须开启allErrors以支持多错误消息展示:

import Ajv from 'ajv';
import ajvErrors from 'ajv-errors';

// 初始化AJV实例,开启所有错误收集
const customAjv = new Ajv({ allErrors: true });
// 注入ajv-errors插件
ajvErrors(customAjv);

3. 修改Schema添加自定义错误消息

在Schema字段中添加errorMessage对象,键对应校验关键字(如minLength、format),值为自定义提示文本。针对代码检查报错,可通过以下方式解决:

方案1:类型断言(快速解决)

export const schema = {
  type: 'object',
  properties: {
    inputControl: {
      type: 'string',
      format: 'email',
      minLength: 7,
      // 自定义错误消息
      errorMessage: {
        minLength: '邮箱长度不能少于7位',
        format: '请输入有效的邮箱地址',
        type: '请输入字符串格式的邮箱'
      }
    },
  },
} as const;

方案2:扩展AJV类型(TS项目推荐)

在项目中添加ajv.d.ts类型声明文件,让TS识别errorMessage关键字:

declare module 'ajv' {
  interface JSONSchemaType<T> {
    errorMessage?: Record<string, string>;
  }
}

方案3:禁用ESLint相关规则

若ESLint报错未知关键字,在.eslintrc中添加忽略配置:

{
  "rules": {
    "json-schema-validator/no-unknown-keyword": ["error", { "ignoreKeywords": ["errorMessage"] }]
  }
}

4. 在JSON Forms中使用自定义AJV实例

将配置好的customAjv通过ajv属性传入JsonForms组件:

import { JsonForms } from '@jsonforms/react';
import { materialRenderers, materialCells } from '@jsonforms/material-renderers';

export default function EmailForm() {
  return (
    <JsonForms
      schema={schema}
      uischema={uischema}
      data={{}}
      renderers={materialRenderers}
      cells={materialCells}
      ajv={customAjv} // 传入自定义AJV实例
    />
  );
}

关键注意事项

  • 必须开启allErrors: true,否则AJV仅返回第一个错误,ajv-errors无法替换所有消息。
  • errorMessage的键必须与Schema中的校验关键字完全匹配(如minLength、format)。
  • 确保ajv和ajv-errors版本兼容,建议使用最新稳定版。

内容的提问来源于stack exchange,提问作者Kiran Anand

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 11:13:15