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

如何在TypeScript版JSON Forms中自定义错误提示信息?

自定义JSON Forms Email格式验证的错误提示

环境信息

  • TypeScript + React
  • JSON Forms 版本:^3.0.0

当前实现代码

TSX 代码

import React, { FC, ReactElement } from "react";

// jsonforms 导入
import { useState } from "react";
import {
  materialRenderers,
  materialCells,
} from "@jsonforms/material-renderers";
import { JsonForms } from "@jsonforms/react";
import schema from "./schema.json";
import uischema from "./uischema.json";
import { createAjv } from "@jsonforms/core";

const InputTextField: FC = (): ReactElement => {
  const [data, setData] = useState({});
  const renderers = [...materialRenderers];
  const ajv = createAjv();

  ajv.addFormat("email", "[a-z0-9]+@[a-z]+.[a-z]{2,3}");

  return (
    <JsonForms
      ajv={ajv}
      schema={schema}
      uischema={uischema}
      data={data}
      renderers={renderers}
      cells={materialCells}
      onChange={({ data, errors }) => setData(data)}
    />
  );
};

export default InputTextField;

Schema 定义

{
  "type": "object",
  "properties": {
    "name": {
      "type": "string",
      "minLength": 3,
      "description": "Please enter your name"
    },
    "birthDate": {
      "type": "string",
      "format": "date"
    },
    "email": {
      "type": "string",
      "description": "Please enter your email.",
      "format": "email"
    }
  },
  "required": ["email"]
}

UI Schema 定义

{
  "type": "VerticalLayout",
  "elements": [{
    "type": "HorizontalLayout",
    "elements": [{
        "type": "Control",
        "scope": "#/properties/name"
      },
      {
        "type": "Control",
        "scope": "#/properties/email"
      },
      {
        "type": "Control",
        "scope": "#/properties/birthDate"
      }
    ]
  }]
}

问题

通过ajv.addFormat("email", "[a-z0-9]+@[a-z]+.[a-z]{2,3}")为email字段添加自定义正则验证后,校验逻辑正常生效,但错误提示为默认内容:

错误提示截图

参考旧教程使用ajv.addKeyword的inline参数自定义错误提示的方法已失效,需解决自定义错误提示的问题。


解决方案

针对JSON Forms 3.0.0及最新AJV版本,提供三种适配方案:

方案一:通过ajv-errors插件自定义格式错误消息

  1. 安装依赖:
npm install ajv-errors
  1. 修改TSX代码,集成插件并配置自定义错误:
import React, { FC, ReactElement } from "react";
import { useState } from "react";
import {
  materialRenderers,
  materialCells,
} from "@jsonforms/material-renderers";
import { JsonForms } from "@jsonforms/react";
import schema from "./schema.json";
import uischema from "./uischema.json";
import { createAjv } from "@jsonforms/core";
import ajvErrors from "ajv-errors";

const InputTextField: FC = (): ReactElement => {
  const [data, setData] = useState({});
  const renderers = [...materialRenderers];
  const ajv = createAjv({ allErrors: true });
  ajvErrors(ajv); // 加载错误插件

  // 自定义email格式验证及错误消息
  ajv.addFormat("email", {
    validate: (email: string) => /[a-z0-9]+@[a-z]+\.[a-z]{2,3}/.test(email),
    errorMessage: "请输入有效的邮箱格式,例如xxx@xxx.com"
  });

  return (
    <JsonForms
      ajv={ajv}
      schema={schema}
      uischema={uischema}
      data={data}
      renderers={renderers}
      cells={materialCells}
      onChange={({ data, errors }) => setData(data)}
    />
  );
};

export default InputTextField;

方案二:在Schema中直接定义错误消息(需配合ajv-errors)

  1. 同方案一安装并启用ajv-errors插件。

  2. 修改Schema,为字段添加errorMessage配置:

{
  "type": "object",
  "properties": {
    "name": {
      "type": "string",
      "minLength": 3,
      "description": "请输入你的姓名",
      "errorMessage": {
        "minLength": "姓名长度不能少于3个字符"
      }
    },
    "birthDate": {
      "type": "string",
      "format": "date"
    },
    "email": {
      "type": "string",
      "description": "请输入你的邮箱",
      "format": "email",
      "errorMessage": "请输入正确格式的邮箱地址"
    }
  },
  "required": ["email"],
  "errorMessage": {
    "required": {
      "email": "邮箱为必填项"
    }
  }
}

方案三:自定义JSON Forms渲染器

如果需要完全自定义错误提示的样式或逻辑,可以编写自定义Control渲染器:

  1. 创建自定义邮箱渲染器:
import { ControlProps, renderErrorMessage } from "@jsonforms/core";
import { TextField } from "@mui/material";
import React from "react";

const CustomEmailRenderer = ({
  data,
  handleChange,
  path,
  errors,
  description
}: ControlProps) => {
  const customError = errors.length > 0 ? "请输入符合格式的邮箱" : undefined;
  return (
    <TextField
      label={description}
      value={data ?? ""}
      onChange={(e) => handleChange(path, e.target.value)}
      error={!!customError}
      helperText={customError}
      variant="outlined"
    />
  );
};

export const customEmailRenderer = {
  tester: (props) => props.schema.format === "email",
  renderer: CustomEmailRenderer
};
  1. 在主组件中引入并使用:
// ... 其他导入
import { customEmailRenderer } from "./CustomEmailRenderer";

const InputTextField: FC = (): ReactElement => {
  // ... 其他代码
  const renderers = [...materialRenderers, customEmailRenderer]; // 添加自定义渲染器
  // ... 其他代码
};

说明

旧教程中ajv.addKeyword的inline参数已在AJV新版本中废弃,上述方案均适配当前最新版本的AJV与JSON Forms,可根据需求选择合适的实现方式。

内容的提问来源于stack exchange,提问作者ernesto casco velazquez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 18:24:56