未显示 react-hook-form 自定义验证消息

react-hook-form custom validation message not showing

我将 react-hook-form 6.8.2 与 React 16.13.1 一起使用,正常验证按预期工作,但在“验证”键内时不正常。

const { trigger, formState, watch, reset } = useFormContext({
    mode: 'all',
});

--

ref={register({
    required: 'This is required',
    minLength: {
        value: 3,
        message: 'Length must be 3 or more',
    },
    validate: {
        always: (value) => value === 1 || 'This should almost always trigger',
    },
    maxLength: {
        value: 5,
        message: 'max 5',
    },
})}

requiredminLengthmaxLength 都有效,但 always 无效。

我试过这个: always: (value) => value === 1 || console.log('This should almost always trigger') 在控制台记录错误

我试过这个:validate: (value) => value === 1 || 'This should almost always trigger' 也什么都不做

为什么 UI 中没有显示验证消息?

验证函数检查您的条件。如果它 returns false 那么可以使用这样的错误机制显示消息:

import React from "react";
import { useForm } from "react-hook-form";

const Example = () => {
  const { handleSubmit, register, errors } = useForm();
  const onSubmit = values => console.log(values);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
  
      <input
        {...register("username", {
          validate: value => value !== "admin" || "Nice try!"
        })}
      />
      {errors.username && errors.username.message} //Here we display the error

      <button type="submit">Submit</button>
    </form>
  );
};

在:V7

不是将 register 函数的结果传递给 ref,而是在输入字段上使用扩展运算符调用 register 函数。在此之后,您需要为此输入起一个唯一的名称,就像每个输入一样。在我的示例中,您的配置工作正常。 https://codesandbox.io/s/react-hook-form-js-forked-js0il?file=/src/App.js

将此答案留给寻找类似解决方案的人。

我使用 react-hook-form@6.8.2react@16.13.1 并使用 RHF 的 useFormContext 钩子根据您的要求制作了一个 CodeSandbox。运行良好,看看:

您的示例代码中有一件事不正确:您将 useForm config options 传递给 useFormContext 挂钩。那是行不通的,您必须将它们传递给 useForm 调用。检查 CodeSandbox 以了解如何将 mode 设置为 'all'。

原来有一个自定义错误呈现 class,隐藏在我们自己的输入字段库深处,没有考虑自定义错误类型。

:(