无法定义打字框自定义错误消息

问题描述 投票:0回答:1

我目前正在第一次学习模式验证,并且正在使用 typebox,但我无法为我的类型定义自定义错误消息。带有这样的道具:

name: Type.String()

我可以附上:

.min(2, { message: "Name must be 2 or more characters long" })

使用 Zod 库,但我仍然没有在 typebox 文档或讨论中找到类似的东西。我选择这个库是因为它是轻量级的,但现在我将研究其他带有react-hook-form的库。预先感谢!

typescript types react-hook-form typebox
1个回答
0
投票

您可以更改默认的打字框错误函数以尊重

message
属性 https://github.com/sinclairzx81/typebox?tab=readme-ov-file#error-function

import {
  DefaultErrorFunction,
  SetErrorFunction,
} from '@sinclair/typebox/errors';

SetErrorFunction((e) => {
  if (e.schema.message && typeof e.schema.message === 'string') {
    return e.schema.message;
  }
  return DefaultErrorFunction(e);
});

然后

Type.String({message: 'example custom error message'})

将引发您想要的错误消息,

尽管从您的示例来看,您可能希望将

message
设置为对象/函数,以便能够使用
e.errorType
值按情况处理错误。

© www.soinside.com 2019 - 2024. All rights reserved.