user7409110
user7409110

Reputation: 529

react-hook-form version 7 validation errors not working

I'm having problems with validation errors using the new react-hook-form version 7 and was wondering if anyone can help (see example linked below).

https://codesandbox.io/s/react-hook-form-adapting-existing-form-forked-n3sis?file=/src/index.js

This all used to work until I updated from v6 to v7. I changed the way register was used, i.e. {...register('name', {required: 'Add this'})} instead of ref={register({required: 'Add this'})} and have updated getting the errors from formState now, i.e. const { formState: { errors }} = useForm(); instead of const { errors } = useForm();.

I'm pretty sure it's got something to do with me using a controlled component rather than just a native html <input /> but can't quite seem to figure it out.

Any help would be hugely appreciated. Thanks.

Upvotes: 2

Views: 2874

Answers (2)

George
George

Reputation: 1050

I wasted around two days just to find out that I was the one who caused the problem.

I disabled submit button if the formState.isValid was false. But the default useForm validation mode is onSubmit. In this mode errors only show up when you submit the form and it was impossible because I disabled the button.

mode change to onBlur or onChange solved the problem

Upvotes: 0

Joris
Joris

Reputation: 2796

You just forgot to pass down props and ref to the input component.

const Input = React.forwardRef(
  ({ error, id, label, required, ...props }, ref) => {
    return (
      <>
        <label htmlFor={id}>{label}</label>
        <input id={id} required={required} {...props} ref={ref} />
        <span style={{ color: "red" }}>{error}</span>
      </>
    );
  }
);

Here is your codesandbox working: https://codesandbox.io/s/react-hook-form-adapting-existing-form-forked-dpxie?file=/src/index.js

Upvotes: 1

Related Questions