All posts
react-hook-formformsvalidationtutorial

Building Validated Forms with react-hook-form and Gwan

Nimesh FonsekaApril 9, 20265 min read
Building Validated Forms with react-hook-form and Gwan

Forms are the backbone of most web apps — sign-ups, settings, checkout flows. They're also notoriously painful to build well. In this post, I'll show you how to combine react-hook-form with Gwan's form components to get strong validation, great UX, and minimal boilerplate.

Why react-hook-form?

react-hook-form is the go-to validation library for React. It's uncontrolled by default (no re-renders per keystroke), has excellent TypeScript support, and integrates cleanly with component libraries through the Controller API.

Installation

npm install react-hook-form

A complete sign-up form

Here's a full example using Gwan's Input, SelectDropdown, Checkbox, and Button components.

Gwan's fields are controlled. Input requires value and is not built with forwardRef, so {...register()} is not a valid prop spread. SelectDropdown and Checkbox own value/checked and onChange as well. Bridge all of them with Controller. Checkbox has no error props — render that message beside it.

Button requires onClick even when type="submit". The empty handler does not replace the form's onSubmit.

"use client";
 
import { useForm, Controller } from "react-hook-form";
import {
  Input,
  SelectDropdown,
  Checkbox,
  Button,
  BUTTON_VARIANTS,
} from "gwan-design-system";
 
type SignUpForm = {
  name: string;
  email: string;
  role: string;
  agreed: boolean;
};
 
export default function SignUpPage() {
  const {
    control,
    handleSubmit,
    formState: { errors },
  } = useForm<SignUpForm>({
    defaultValues: {
      name: "",
      email: "",
      role: "",
      agreed: false,
    },
  });
 
  const onSubmit = (data: SignUpForm) => {
    console.log(data);
  };
 
  return (
    <form
      onSubmit={handleSubmit(onSubmit)}
      className="flex flex-col gap-5 max-w-md"
    >
      <Controller
        name="name"
        control={control}
        rules={{ required: "Name is required" }}
        render={({ field }) => (
          <Input
            label="Full name"
            placeholder="Nimesh Fonseka"
            value={field.value}
            onBlur={field.onBlur}
            onChange={(e) => field.onChange(e.target.value)}
            isError={!!errors.name}
            errorMessage={errors.name?.message}
          />
        )}
      />
 
      <Controller
        name="email"
        control={control}
        rules={{
          required: "Email is required",
          pattern: { value: /\S+@\S+\.\S+/, message: "Invalid email" },
        }}
        render={({ field }) => (
          <Input
            label="Email"
            type="email"
            placeholder="you@example.com"
            value={field.value}
            onBlur={field.onBlur}
            onChange={(e) => field.onChange(e.target.value)}
            isError={!!errors.email}
            errorMessage={errors.email?.message}
          />
        )}
      />
 
      <Controller
        name="role"
        control={control}
        rules={{ required: "Please select a role" }}
        render={({ field }) => (
          <SelectDropdown
            label="Role"
            options={[
              { label: "Developer", value: "developer" },
              { label: "Designer", value: "designer" },
              { label: "Product Manager", value: "pm" },
            ]}
            value={field.value}
            onChange={(value) => field.onChange(value)}
            isError={!!errors.role}
            errorMessage={errors.role?.message}
          />
        )}
      />
 
      <Controller
        name="agreed"
        control={control}
        rules={{ required: "You must agree to the terms" }}
        render={({ field }) => (
          <div className="flex flex-col gap-1">
            <Checkbox
              label="I agree to the terms and conditions"
              checked={field.value}
              onChange={(checked) => field.onChange(checked)}
            />
            {errors.agreed?.message ? (
              <p role="alert" className="text-danger text-xs">
                {errors.agreed.message}
              </p>
            ) : null}
          </div>
        )}
      />
 
      <Button
        type="submit"
        variant={BUTTON_VARIANTS.PRIMARY}
        label="Create account"
        onClick={() => {}}
      />
    </form>
  );
}

How it works

Controlled components: Controller

Input and TextArea render a native <input> or <textarea>, but both require value and neither forwards a ref. register() returns { name, onChange, onBlur, ref } and does not provide value, so spreading it onto Input or TextArea fails to type-check. Input's props extend HTMLAttributes, which has no name attribute — Controller's own name is what react-hook-form tracks. Pass value and onChange through Controller:

"use client";
 
import { Controller, useForm } from "react-hook-form";
import { Input } from "gwan-design-system";
 
export function EmailField() {
  const {
    control,
    formState: { errors },
  } = useForm<{ email: string }>({ defaultValues: { email: "" } });
 
  return (
    <Controller
      name="email"
      control={control}
      rules={{ required: "Email is required" }}
      render={({ field }) => (
        <Input
          label="Email"
          value={field.value}
          onBlur={field.onBlur}
          onChange={(e) => field.onChange(e.target.value)}
          isError={!!errors.email}
          errorMessage={errors.email?.message}
        />
      )}
    />
  );
}

TextArea uses the same shape: value, onChange with e.target.value, isError, and errorMessage.

SelectDropdown takes value: string and onChange: (option: string) => void. Checkbox takes checked: boolean and onChange: (checked: boolean) => void. Neither accepts a ref from register(), so they use Controller the same way — see the sign-up form above.

Showing errors

Input, TextArea, and SelectDropdown accept isError and errorMessage. Set isError when react-hook-form has an error for that field, and pass errors.fieldName?.message as errorMessage. There is no error prop.

Checkbox has neither prop. Render the message yourself, next to the control, as the sign-up form does with role="alert".

Schema validation with Zod

For complex forms, pair react-hook-form with Zod for schema-based validation. Zod 4's email check is z.email() (z.string().email() still runs, and is deprecated):

npm install zod @hookform/resolvers
"use client";
 
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
 
const schema = z.object({
  email: z.email("Invalid email"),
  password: z.string().min(8, "Minimum 8 characters"),
});
 
export function usePasswordForm() {
  return useForm({
    resolver: zodResolver(schema),
    defaultValues: { email: "", password: "" },
  });
}

This keeps all your validation logic in one place and gives you full type inference. Wire each Gwan field with Controller, as in the sign-up form. Leave the useForm generic off when a resolver is present so Zod's input and output types are inferred.

Summary

Componentreact-hook-form method
InputController (value is required)
TextAreaController (value is required)
SelectDropdownController
CheckboxController; render the error text yourself
RadioButtonController (selectedValue / onChange)

Gwan's form fields are controlled components, so they use Controller. Where the component supports them, pass isError and errorMessage. Checkbox and RadioButton do not, so the message sits beside the control.


Have a question or want to see another integration? Reach out on GitHub.

Share this article

LinkedInX / Twitter

Written by

Nimesh Fonseka

More posts →