首页 > 解决方案 > 以反应钩子形式使用每个验证规则的错误消息数组

问题描述

使用 react-hook-form 版本 7.11.1。

我有一个简单的控件,当它无效时,它会在每个验证规则中显示多条错误消息。当我注册这个控件时,我提供了一个带有自定义验证功能的“验证”选项。从 validate option contract 我看到我的自定义验证函数应该返回ValidateResult类型。这种类型可以是:消息 | 消息[] | 布尔值 | 未定义(其中 Message 是字符串)。所以我假设如果控制无效,我可以返回错误消息数组。但是如果我返回的不是字符串而是数组,我将无法在任何地方访问我的错误消息:formState.errors。归档名称.mesage为空。

有没有办法使用错误消息数组在界面中显示它们?

我的简单组件如下:

export const ControlWithErrorsExample = () => {
    const {
        register,
        formState: { errors },
    } = useForm({
        mode: 'onChange',
    });

    const { testValue: testValueError } = errors;

    const validateField = (v: string): ValidateResult => {
        if (v.length > 3) {
            return ['Incorrect value', 'Max length should be equal or less than 3'];
        }

        return undefined;
    };

    useEffect(() => {
        console.log(`I need to get access to my error messages array but got: ${testValueError?.message}`);
    }, [testValueError]);

    return <input type="text" {...register('testValue', { validate: (v) => validateField(v) })} />;
};

标签: reactjsreact-hook-form

解决方案


验证功能无法满足您的需求。

为什么Message[]
这种类型由解析器使用,解析器是满足您需求的唯一方法。您可以构建自己的或使用我们的:https ://github.com/react-hook-form/resolvers

以下是消息数组的示例:

"birthYear": Object {
  "message": "Expected number, received string",
  "ref": undefined,
  "type": "invalid_type",
  "types": Object {
    "invalid_type": Array [
      "Expected number, received string",
      "Expected undefined, received string",
    ],
    "invalid_union": "Invalid input",
  },
},

Zod 快照中的示例

还有一件事,要出现所有错误,您应该使用criteriaMode: 'all'withuseForm

https://react-hook-form.com/api/useform

随意打开一个 RFC:https ://github.com/react-hook-form/react-hook-form/discussions


推荐阅读