react-hook-form: How validate object works

Viewed 1285

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

2 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)

To apply multiple validations, you can build a custom hook as a resolver. A custom hook can easily integrate with yup/Joi/Superstruct as a validation method, and be used inside validation resolver.

You can find more doc and examples here: https://react-hook-form.com/advanced-usage/ in the section: Custom Hook with Resolver

I recommend you yup.

Related