Step Level Up
M
Mahadev Mandal

· min read

Validate Checkbox and Radio Groups with React Hook Form (Without Yup)

Introduction

When building forms in React, validation is a crucial aspect to ensure users provide correct input. While libraries like Yup are commonly used to handle validation, it's possible to achieve form validation using just React Hook Form's built-in features. This article will focus on validating checkbox and radio groups using React Hook Form without relying on external validation libraries.

Why Avoid Yup?

Yup is an excellent validation library that pairs well with React Hook Form for handling complex validations. However, for simpler scenarios, using Yup might be overkill, especially if you want to keep your form-handling code lean. React Hook Form provides built-in validation that can handle most use cases, including checkbox and radio group validation.

Setting Up React Hook Form

To demonstrate the power of React Hook Form without additional libraries, let's look at how to validate checkbox and radio inputs. Below is an example code that uses React Hook Form to validate these form elements.

import "./styles.css";
import { useForm } from "react-hook-form";

export default function App() {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    defaultValues: {
      checkbox: [],
      radio: "",
    },
  });

  const submit = (data) => {
    console.log("Submitted data:", data);
  };

  return (
    <div className="App">
      <h2>Validate Checkbox and Radio Groups with React Hook Form</h2>
      <div className="container">
        {/* Checkbox group */}
        <div className="form-group">
          <span>
            Checkbox A
            <input
              type="checkbox"
              value="A"
              {...register("checkbox", {
                required: "Select at least one checkbox",
              })}
            />
          </span>
          <span>
            Checkbox B
            <input type="checkbox" value="B" {...register("checkbox")} />
          </span>
          <span>
            Checkbox C
            <input type="checkbox" value="C" {...register("checkbox")} />
          </span>
        </div>
        {/* Display error messages */}
        {errors.checkbox && <p className="error">{errors.checkbox.message}</p>}
      </div>
      <div className="container">
        {/* Radio group */}
        <div className="form-group">
          <span>
            Radio A
            <input
              type="radio"
              value="A"
              {...register("radio", { required: "Select at least one radio" })}
            />
          </span>
          <span>
            Radio B
            <input type="radio" value="B" {...register("radio")} />
          </span>
          <span>
            Radio C
            <input type="radio" value="C" {...register("radio")} />
          </span>
        </div>
        {/* Display error messages */}
        {errors.radio && <p className="error">{errors.radio.message}</p>}
      </div>
      {/* Submit button */}
      <button onClick={handleSubmit(submit)}>Submit</button>
    </div>
  );
}

Explanation of the Code

In this example, we're creating a simple form with a group of checkboxes and a group of radio buttons. Here's a breakdown of how validation works:

  • Checkbox Group Validation:

    • The checkboxes are registered with register("checkbox", { required: "Select at least one checkbox" }). This configuration enforces that at least one checkbox must be selected.
    • If no checkbox is selected, an error message will be displayed, thanks to React Hook Form's errors object.
  • Radio Group Validation:

    • Similar to the checkboxes, the radio buttons are registered with register("radio", { required: "Select at least one radio" }). This ensures that a user must select one of the radio options.
    • If no radio button is selected, an error message is displayed.

Styling the Form

To enhance the user experience, we apply some basic styles using CSS:

.App {
  padding: 0 20px;
}

.form-group {
  display: flex;
}

.form-group span {
  padding-right: 20px;
  display: flex;
  align-items: center;
  font-size: 16px;
}

.form-group span input {
  margin-left: 8px;
  height: 16px;
  width: 16px;
}

.error {
  margin: 0px;
  color: red;
}

.container {
  margin-bottom: 18px;
}

Try It Out

You can test the code in a live environment using the embedded CodeSandbox below:

Conclusion

React Hook Form provides robust form handling capabilities with built-in validation, eliminating the need for external libraries like Yup in many cases. This example demonstrates how to validate checkbox and radio groups with minimal configuration. By utilizing React Hook Form, you can simplify your forms and keep your codebase lightweight.

Additional Considerations

  • Advanced Validation: For more complex validation scenarios, you might still want to consider Yup. However, for basic form needs, React Hook Form's built-in features are more than sufficient.
  • Custom Error Messages: React Hook Form allows you to customize error messages, as shown in the example. Tailor these messages to your application's needs for a better user experience.

With React Hook Form, you can effectively manage form state and validation without overcomplicating your codebase. Happy coding!

Comments

Loading...

Mahadev Mandal

Written by Mahadev Mandal

I am a web developer with expertise in HTML, CSS, Tailwind, React.js, Next.js, Gatsby, API integration, WordPress, Netlify functions, the MERN stack, fullstack development, and NestJS.