Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 62

Custom Form Hook: Validation & Error Handling

Recommended resources

Hello! Welcome back to our module on creating reusable logic with custom hooks.

In our last lesson, you built a clean and efficient useForm hook that elegantly managed form state, a handleChange function, and a resetForm utility. This was a fantastic first step in abstracting away the boilerplate of form management.

Today, we will address the next critical piece of the puzzle: validation. Our goal is to extend a custom form hook to include validation and error handling logic. By the end of this lesson, you'll be able to build forms that not only capture data but also ensure its integrity and provide clear feedback to the user, a non-negotiable feature for any production-quality application.

We'll explore two powerful approaches:

  1. Building a self-contained validation engine inside our custom hook.
  2. Leveraging a professional-grade, schema-based validation library called Zod to make our validation type-safe and highly reusable.

The Need for Validation and Error Feedback

A form without validation is like a doorway with no lock. It's crucial for both data integrity on the backend and for a good user experience on the frontend. A user should know what they did wrong and where.

Custom Form Validation Hook in React
An example of inline validation, showing a specific error message for an input field and disabling the submit button until the form is valid.

Let's enhance our hook to provide this kind of feedback.


Approach 1: A Custom Validation Engine

First, we'll build our own validation logic. This approach gives you full control and is a great way to understand the underlying mechanics. A powerful pattern in React is the composition of hooks. Instead of bloating our useForm hook, we can create a separate useValidation hook and have useForm use it internally.

The article "How to Create Reusable Logic with Custom React Hooks" provides an excellent implementation of this pattern.

How to Create Reusable Logic with Custom React Hooks

This article from dev.to by Cheryl Tan demonstrates how to compose two custom hooks, useForm and useValidation, to create a complete form handling solution. We will study its implementation closely.

Read through the following three sections: PersonalDetailsForm.jsx: Pay attention to the validationSchema object. This is how we'll define our rules. useForm.js Custom Hook: Notice how it imports and uses useValidation, passing the validationSchema to it. This is hook composition in action. useValidation.js Custom Hook: This is the core of the validation logic. Focus on the errors state, the validateAllFields function for submission, and the validationProps object that's returned to the component.

Synthesizing the useValidation Hook

Let's codify the logic from the article into a type-safe useValidation.ts hook. Your background in software engineering will help you appreciate how this separates the validation concern from the state management concern.

// src/hooks/useValidation.ts

import { useState, useCallback }s from 'react';

// Define the structure for a single validation rule
interface ValidationRule<T> {
  validator: (value: T) => boolean;
  message: string;
}

// The schema is an object where keys match form data keys,
// and values are an array of validation rules.
type ValidationSchema<T> = {
  [K in keyof T]?: ValidationRule<T[K]>[];
};

export function useValidation<T>(
  formData: T,
  validationSchema: ValidationSchema<T>
) {
  const [errors, setErrors] = useState<Record<string, string[]>>({});

  // Validates a single field based on its rules in the schema
  const validateField = (name: keyof T, value: T[keyof T]) => {
    const rules = validationSchema[name];
    if (!rules) return [];

    const fieldErrors: string[] = [];
    for (const rule of rules) {
      if (!rule.validator(value)) {
        fieldErrors.push(rule.message);
      }
    }
    return fieldErrors;
  };

  // Validates all fields in the form, typically on submit.
  // Returns true if the form is valid, false otherwise.
  const validateAllFields = useCallback(() => {
    const newErrors: Record<string, string[]> = {};
    let isFormValid = true;

    for (const key in validationSchema) {
      const fieldErrors = validateField(key as keyof T, formData[key as keyof T]);
      if (fieldErrors.length > 0) {
        newErrors[key] = fieldErrors;
        isFormValid = false;
      }
    }

    setErrors(newErrors);
    return isFormValid;
  }, [formData, validationSchema]);

  // A helper function to generate props for an input field
  const getValidationProps = useCallback(
    (name: string) => ({
      // We pass the first error message for simplicity
      errorMessage: errors[name]?.[0],
      // isValid can be used to style the input (e.g., a red border)
      isValid: !errors[name] || errors[name].length === 0,
    }),
    [errors]
  );

  return { errors, validateAllFields, getValidationProps };
}

Composing into useForm

Now, let's update our useForm hook from the previous lesson to consume this new useValidation hook.

// src/hooks/useForm.ts (Updated)
import { useState, useCallback } from 'react';
import { useValidation, ValidationSchema } from './useValidation'; // Import our new hook

export function useForm<T>(
  initialValues: T,
  onSubmitCallback: (values: T) => void,
  validationSchema: ValidationSchema<T> = {}
) {
  const [values, setValues] = useState<T>(initialValues);
  
  // Here is the composition!
  const { errors, validateAllFields, getValidationProps } = useValidation(values, validationSchema);

  const handleChange = useCallback((event: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value, type } = event.target;
    const newValue = type === 'checkbox' ? (event.target as HTMLInputElement).checked : value;

    setValues(prev => ({ ...prev, [name]: newValue }));
  }, []);

  const handleSubmit = useCallback((event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (validateAllFields()) {
      onSubmitCallback(values);
    } else {
      console.log('Validation failed');
    }
  }, [validateAllFields, onSubmitCallback, values]);

  const resetForm = useCallback(() => {
    setValues(initialValues);
  }, [initialValues]);

  return {
    values,
    errors,
    handleChange,
    handleSubmit,
    resetForm,
    getValidationProps,
  };
}

This is a beautiful example of the power of custom hooks. The useForm hook now has validation capabilities, but its own code remains focused and clean because the complex validation logic is neatly encapsulated in useValidation.


Approach 2: Schema-Based Validation with Zod

Our custom validation engine is powerful, but for complex applications, defining validation rules manually can become verbose. Furthermore, what if you need to run the same validation on the server? You'd have to write the logic twice, which is a maintenance nightmare.

This is where schema-based validation libraries shine. We will use Zod, a modern, TypeScript-first library that has become an industry standard.

Form Validation Custom Hook with Zod in React + TypeScript
Zod allows you to declare a single "schema" for your data, which acts as the single source of truth for validation, both on the client and server.

The main advantages of Zod are:

  • Type Safety: It can infer TypeScript types directly from your validation schema. No more manually keeping types and validation rules in sync!
  • Reusability: The schema is just a JavaScript object, so it can be defined in a shared file and used in your frontend, your backend API, and anywhere else you need to validate that data structure.
  • Expressive API: It provides a rich, chainable API for defining rules, from simple string checks to complex, interdependent object validations.

To understand how to define a schema and use it for validation, let's watch a segment from an excellent tutorial by ByteGrad.

React Hook Form (+ Zod) - Complete Tutorial

The video 'React Hook Form (+ Zod) - Complete Tutorial' explains why and how to use Zod. Although the video uses the react-hook-form library, the principles of defining a Zod schema and its benefits are universal and apply directly to our custom hook.

Watch from 18:45 to 25:35. Focus on these key concepts: The 'Why': Understand the benefit of a single schema for client and server validation. Creating a Schema: See how z.object() is used to define the shape and rules (z.string().email(), z.string().min(10)). Cross-Field Validation: Pay close attention to how .refine() is used to check if the two password fields match. This is a powerful feature for complex rules. Type Inference: Notice how z.infer<typeof schema> is used to automatically generate a TypeScript type from the schema.

Integrating Zod into Our useForm Hook

Now, let's create a new version of useForm that is powered by Zod. Instead of a validationSchema object, it will accept a Zod schema.

First, you'll need to install Zod: npm install zod.

Here's how our new, more powerful useForm hook looks:

// src/hooks/useFormWithZod.ts
import { useState, useCallback } from 'react';
import { z, ZodSchema, ZodError } from 'zod';

// A generic to format Zod's errors into a more usable object
type FormattedZodErrors<T> = {
  [K in keyof T]?: string;
};

export function useFormWithZod<T extends z.ZodRawShape>(
  schema: ZodSchema<T>,
  initialValues: z.infer<typeof schema>,
  onSubmitCallback: (values: z.infer<typeof schema>) => void
) {
  const [values, setValues] = useState(initialValues);
  // Errors will now be in a simpler { fieldName: 'error message' } format
  const [errors, setErrors] = useState<FormattedZodErrors<z.infer<typeof schema>>>({});

  const handleChange = useCallback((event: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value, type } = event.target;
    const newValue = type === 'checkbox' ? (event.target as HTMLInputElement).checked : value;

    setValues(prev => ({ ...prev, [name]: newValue }));
  }, []);

  const handleSubmit = useCallback((event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    // Use Zod's .safeParse to validate without throwing an error
    const result = schema.safeParse(values);

    if (result.success) {
      // If validation is successful, clear errors and run the callback
      setErrors({});
      onSubmitCallback(result.data);
    } else {
      // If validation fails, format Zod's complex error object
      const formattedErrors = result.error.flatten().fieldErrors;
      const newErrors: FormattedZodErrors<z.infer<typeof schema>> = {};

      for (const key in formattedErrors) {
        // Take only the first error message for each field
        newErrors[key as keyof z.infer<typeof schema>] = formattedErrors[key]?.[0];
      }
      setErrors(newErrors);
    }
  }, [schema, values, onSubmitCallback]);

  const resetForm = useCallback(() => {
    setValues(initialValues);
    setErrors({});
  }, [initialValues]);

  return {
    values,
    errors,
    handleChange,
    handleSubmit,
    resetForm,
  };
}
Test your understanding!

In the handleSubmit function of our useFormWithZod hook, we clear existing errors with setErrors({}) before calling the onSubmitCallback. Why is this small step important for a good user experience?

Show answer

Imagine a user fills out the form, gets a validation error, and then corrects it. If they submit successfully, but we forget to clear the old errors, the error messages might remain on the screen even though the submission was successful. Clearing the errors on a successful submission ensures the UI is always in a correct and clean state, reflecting that the previous issues have been resolved.

Using the Zod-Powered Hook

Using this hook is incredibly clean. The component no longer knows or cares how validation is performed; it just defines a schema and gets back the state and handlers.

// src/components/SignUpForm.tsx
import React from 'react';
import { z } from 'zod';
import { useFormWithZod } from '../hooks/useFormWithZod';

// 1. Define the schema and infer the type
const SignUpSchema = z.object({
  email: z.string().email({ message: "Invalid email address" }),
  password: z.string().min(8, { message: "Password must be at least 8 characters" }),
  confirmPassword: z.string(),
}).refine((data) => data.password === data.confirmPassword, {
  message: "Passwords do not match",
  path: ["confirmPassword"], // Attach error to the confirmPassword field
});

type SignUpData = z.infer<typeof SignUpSchema>;

const initialData: SignUpData = {
  email: '',
  password: '',
  confirmPassword: '',
};

export function SignUpForm() {
  // 2. Use the hook with the schema
  const { values, errors, handleChange, handleSubmit, resetForm } = useFormWithZod(
    SignUpSchema,
    initialData,
    (data) => {
      console.log('Form submitted successfully:', data);
      alert(`Account created for ${data.email}!`);
      resetForm();
    }
  );

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>Email</label>
        <input name="email" value={values.email} onChange={handleChange} />
        {errors.email && <p style={{color: 'red'}}>{errors.email}</p>}
      </div>
      <div>
        <label>Password</label>
        <input type="password" name="password" value={values.password} onChange={handleChange} />
        {errors.password && <p style={{color: 'red'}}>{errors.password}</p>}
      </div>
      <div>
        <label>Confirm Password</label>
        <input type="password" name="confirmPassword" value={values.confirmPassword} onChange={handleChange} />
        {errors.confirmPassword && <p style={{color: 'red'}}>{errors.confirmPassword}</p>}
      </div>
      <button type="submit">Sign Up</button>
    </form>
  );
}

This pattern is extremely scalable and is the foundation of many production-level React applications.


Conclusion

Today you've taken our simple useForm hook and evolved it into a powerful, production-ready tool for handling forms. You've seen how to abstract complex logic, compose hooks, and integrate external libraries to create robust and maintainable code.

Key Takeaways:

  • Validation is Key: Forms need validation for data integrity and user feedback. Error messages should be clear and field-specific.
  • Hook Composition: You can build complex functionality by having custom hooks use other custom hooks (e.g., useForm using useValidation). This follows the single-responsibility principle.
  • Manual vs. Schema-Based: A manual validation engine offers full control, while a schema-based library like Zod provides superior type safety, reusability (client/server), and a more declarative API for complex forms.
  • Zod Workflow: The pattern of defining a schema, inferring a type, and using .safeParse() for validation is a modern, robust way to handle data in a TypeScript application.

Preview of the Next Lesson:
So far, our state has been ephemeral—it disappears when the user refreshes the page. What if we want to persist data, like user preferences or an unfinished form? In the next lesson, you will create a useLocalStorage hook for persisting state across browser sessions, another indispensable tool in your custom hook toolkit.