【问题标题】:react-hook-form error message not showingreact-hook-form 错误消息未显示
【发布时间】:2021-10-13 20:16:00
【问题描述】:

我试图让错误显示在我的页面上,但没有任何反应,我在我的console.log() 中得到一个undefined(如果没有填写任何内容)

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

export default function ContactForm() {
  const { register, handleSubmit, watch, formState: { errors } } = useForm();
  const onSubmit = data => console.log(data);

  console.log(watch("example")); // watch input value by passing the name of it

  return (
    <div className="md:w-4/12 ml-auto mr-auto translate-x-1/2 mt-24 w-9/12">
        <form onSubmit={handleSubmit(onSubmit)} className="bg-red-500 p-4">
            {/* register your input into the hook by invoking the "register" function */}
            <label className='text-lg'> email:</label>
                <input label="email" id="email" className="block w-full" {...register("email", {required: true})} />
            {/* include validation with required or other standard HTML validation rules */}
            <label className='text-lg mb-4'>vraag:</label>
                <textarea id="tekst" type="textarea" className="block box-border w-full h-52" {...register("vraag", { required: true })} />

            {/* errors will return when field validation fails  */}
            {errors.exampleRequired && <span className="bg-yellow-400">TEST TEST TEST TEST TEST TEST TEST TEST TEST</span>}
            
            <input type="submit" value="versturen" className="pl-2 mt-2 pr-2 block ml-auto mr-auto cursor-pointer"/>
        </form>
    </div>
  );
}

【问题讨论】:

  • 您使用的是什么版本的 RHF?
  • 我今天安装了,所以最新的

标签: reactjs react-hook-form


【解决方案1】:

您需要像这样自己指定错误消息:

{...register("email", { required: "please enter email" })}

那么当出现任何错误时,这就是你显示消息的方式:

{errors.email && (
  <span className="bg-yellow-400">{errors.email.message}</span>
)}

如果您只想一次显示所有字段的一条错误消息:

{Object.keys(errors)
  .reverse()
  .reduce(
    (a, field) =>
      errors[field] ? (
        <span className="bg-yellow-400">{errors[field].message}</span>
      ) : (
        a
      ),
    null
  )}

现场演示

参考

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 2021-08-18
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    相关资源
    最近更新 更多