React-hook-form conditional validation of text field, based on if another checkbox is checked?

Viewed 10415

I'm trying to add a validation rule to a text field, where if a separate checkbox in the form is checked, the field is required to be a non-empty string in order for the form to submit.

Here's a link to what I have so far: https://codesandbox.io/s/magical-hypatia-n7o5w

I need the final text input in the form ("tiger_type") to require a value entered only if the checkbox input with id 'tiger' is checked.

I'm new to react and react-hooks-form, so any pointers will be appreciated. Thanks in advance.

1 Answers

Use the validation object of the callback functions that react-hook-form provides. Fully working solution https://codesandbox.io/s/admiring-morning-ljnvk?file=/src/App.js

import { useForm } from 'react-hook-form';
// ... your component implementation 
const { getValues, getValues } = useForm(); 

return (
  <form onSubmit={handleSubmit}>
    <input ref={register} name="username" />
    <input
      ref={register({
        validate: {
          required: value => {
            if (!value && getValues('username')) return 'Required when username is provided';
            return true;
          },
        },
      })}
      name="email"
      type="text"
    />
 </form>
);

Note: at the time of writing this solutions is supported by v5 and v6 of react-hook-form https://react-hook-form.com/api#register

Related