reactjs - 以反应钩子形式使用每个验证规则的错误消息数组
问题描述
使用 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) })} />;
};
解决方案
验证功能无法满足您的需求。
为什么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",
},
},
还有一件事,要出现所有错误,您应该使用criteriaMode: 'all'
withuseForm
https://react-hook-form.com/api/useform
随意打开一个 RFC:https ://github.com/react-hook-form/react-hook-form/discussions
推荐阅读
- javascript - 请求太重时出现 NodeJS CORS 错误(文件上传)
- python - 如何从容器类型中区分函数类型?
- javascript - 莉莉的作业——hackerrank挑战javascript
- powershell - 使用 selenium chrome 驱动程序下载 .xml 文件
- javascript - JS:异步函数隐含地解开承诺?
- domain-driven-design - C# DDD:更改篮子项目数量(如果可用)
- c# - C#-Xamarin:在设备上创建一个 .txt 文件
- vue.js - vue-axios BASE_URL 未应用
- java - 我不能将 JavaFX 控制器移动到不是基本包的包中。马文
- linux - Unix: 'su user' 不工作并且在 SSH 中保持 root 如果条件