1

I would like to know how to disable a button only when both Name and State in the following code are empty.In other words, I would like to know how to make it so that the button can be pressed only when both name and state are entered, regardless of whether the email is null or not.

import React from "react";
import { useForm, SubmitHandler } from "react-hook-form";

type FormValues = {
  name: string;
  state: string;
  email: string;
};

export default function App() {
  const { register, handleSubmit } = useForm<FormValues>();
  const onSubmit: SubmitHandler<FormValues> = data => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("name")} />
      <input {...register("state")} />
      <input type="email" {...register("email")} />

      <input type="submit" />
    </form>
  );
}
musako
  • 897
  • 2
  • 10
  • 26
  • Does this answer your question? [How to conditionally disable the submit button with react-hook-form?](https://stackoverflow.com/questions/65255298/how-to-conditionally-disable-the-submit-button-with-react-hook-form) – indyteo Feb 26 '23 at 17:40
  • @indyteo Thanks for commenting! I checked this question as well. I think this method is not working because if you don't fill out all the inputs, the button will be DISABLE. – musako Feb 26 '23 at 18:13
  • I'm sorry I didn't noticed the first part of your question. According to [this docs](https://react-hook-form.com/api/useformstate), you can pass a `string[]` parameter `name` to the `useFormState(...)` hook to only watch certain input. I personally never tried it but if you want I can have a look and write a complete answer ;) – indyteo Feb 26 '23 at 18:26

1 Answers1

1

You can achieve that with checking the property isValid of the formState object. Disable the button when isValid is false and set the required property within the register method to true for name and state. The button is disabled this way whenever name or state are empty, regardless of the email input.

Here is a working version:

import React from "react";
import { useForm, SubmitHandler } from "react-hook-form";

type FormValues = {
  name: string;
  state: string;
  email: string;
};

export default function App() {
  const { register, handleSubmit, formState } = useForm<FormValues>();
  const onSubmit: SubmitHandler<FormValues> = data => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("name", {required: true})} />
      <input {...register("state", {required: true})} />
      <input type="email"   {...register("email")}/>

      {/* Disable input button if both Name and State are empty */}
      <input type="submit" disabled={!formState.isValid} />
    </form>
  );
}
kevinunger
  • 334
  • 5
  • 13