Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-hook-form: How validate object works

I see in the docs

<input
  {...register("test1", {
    validate: {
      positive: v => parseInt(v) > 0,
      lessThanTen: v => parseInt(v) < 10,
      checkUrl: async () => await fetch(),
    }
  })}
/>

So here how can i show different messages for each validation.

like number is -5, then i show

"Number is not positive"
"Number less than 10"

HOw to access each error positive and lessThanTen

like image 957
naveen raje Avatar asked Sep 19 '25 11:09

naveen raje


1 Answers

Per default RHF will only show one error per field, so if there are multiple you will you don't have to loop over them. You can just use the errors object provided by RHF and access the name of your field and then the message property.

If you need to have all errors to be shown simultaneously you can set the config criteriaMode, check the docs here for more info.

function App() {
  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm();

  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label htmlFor="test1">Test Field</label>
      <input
        {...register("test1", {
          validate: {
            positive: (v) => parseInt(v) > 0 || "Number is not positive",
            lessThanTen: (v) => parseInt(v) < 10 || "Number less than 10",
            checkUrl: async () => {
              const result = await Promise.resolve(true);

              return result || "result was false so show this message";
            }
          }
        })}
      />
      {errors.test1 && <p>{errors.test1.message}</p>}

      <input type="submit" />
    </form>
  );
}

Edit React Hook Form - Custom validation (forked)

like image 63
knoefel Avatar answered Sep 23 '25 13:09

knoefel