Where does my error message show up with React Forms?

49 views Asked by At

If I write this in React:

  <input
    type="text"
    style={{ width: "50px" }}
    required
    placeholder="###"
    pattern="\d{3}"
  />

`

And I try to submit the form while I don't follow the 3 digit pattern, a little tab comes down with the words "Please follow requested format".

If I use these two imports: import { useForm } from "react-hook-form"; import { ErrorMessage } from "@hookform/error-message";

And then try this:

<input {...register("first", { required: true, pattern: { value: /\d{3}/, message: "kljlk" } })} />

It stops the form from getting submitted if I did not follow the pattern, but where does the "message" go? I don't see the same little tab the above code generates.

1

There are 1 answers

3
Dick Larsson On

You can display error messages using the errors object provided by react-hook-form. This object contains any errors that occurred during validation, and you can reference it to display the error message wherever you like in your component.

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

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

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

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        {...register('first', {
          required: 'This field is required',
          pattern: {
            value: /\d{3}/,
            message: 'Please enter exactly 3 digits'
          }
        })}
      />
      {/* Display error message */}
      {errors.first && <p>{errors.first.message}</p>}

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

export default MyForm;