major697
major697

Reputation: 1862

react-hook-form can't correctly validation with value and onChange after submit

I have component:

const FormComponent = () => {
  const { register, handleSubmit, errors } = useForm();

  const [val, setVal] = useState("");

  const handleSubmitForm = () => console.log("send!");

  const handleChange = (e) => {
    setVal(e.target.value);
  };

  return (
    <form onSubmit={handleSubmit(handleSubmitForm)}>
      <input
        type="text"
        name="test"
        value={val}
        ref={register({ required: "The field is required." })}
        onChange={handleChange}
      />
      {errors.test && errors.test.message}
      <button type="submit">Send</button>
    </form>
  );
};

When I click "Submit", react-hook-form show me error message: 'The field is required. '. And when I want write word "TEST" and next I try remove this text by for example select all text and click Backspace button, then I can't remove this text from input, but message about empty value is showing.

How I can use react-hook-form with value and onChange event?

Demo codesandbox

Upvotes: 2

Views: 6039

Answers (2)

Said Pc
Said Pc

Reputation: 655

you must use mode:"onChange" when calling useForm

code example :

const { register, handleSubmit, formState: { errors } } = useForm({
    resolver: yupResolver(schema),
    mode: "onBlur",
    // mode:"onChange",
  });

Upvotes: 0

Dejan Sandic
Dejan Sandic

Reputation: 451

No need to have value and onChange. You can use the uncontrolled form, and if you need a value of one of the inputs, you can simply watch it ;-)

const FormComponent = () => {
   const { register, handleSubmit, watch, errors } = useForm(); 
   const handleSubmitForm = (data) => console.log(data);
 
   const valueOfTest = watch('test');

   useEffect(() => {
      //consider this to be onchange function
      doSomething(valueOfTest);
   }, [valueOfTest]);
 
   return (
     <form onSubmit={handleSubmit(handleSubmitForm)}>
       <input
         type="text"
         name="test"
         ref={register({ required: "The field is required." })}
       />
       {errors.test && errors.test.message}
       <button type="submit">Send</button>
     </form>
   );
 };

Upvotes: 1

Related Questions