Hello! Welcome to your next lesson in the "Forms and Event Handling" module.
In our last session, we took control of form submission, using e.preventDefault() to stop the default browser reload and handle the submission process within our React application. We now have a clean formData object ready to go. But what if that data is incomplete or incorrect?
This lesson directly addresses that question, focusing on the learning outcome: Implement client-side form validation and provide clear user feedback. We will explore how to enforce rules on user input before submission and how to communicate any issues back to the user in a helpful way.
Given your proficiency in TypeScript and general programming principles, we'll look at this from two angles: first, a fundamental approach using built-in browser features, and second, a more robust, production-grade approach using popular libraries that leverage strong typing.

1. The Foundational Approach: HTML5 Validation
Before reaching for any libraries, it's essential to understand the validation capabilities built directly into HTML. These are simple, declarative, and often sufficient for basic forms.
Key HTML5 attributes for validation include:
required: The field must not be empty.type="email"ortype="url": The input must match the format of an email address or URL.minLengthandmaxLength: For string inputs.minandmax: For number inputs.pattern: Accepts a regular expression to test the input against. This is very powerful for custom formats (e.g., specific postal codes or usernames).
Your background in programming and data structures means you're already familiar with the concept of constraints and patterns; HTML5 simply provides a declarative way to express them.
However, relying on the browser's default error messages (like the pop-up bubbles) offers limited control over styling and user experience. A better approach in React is to use these attributes for the validation logic but create our own UI for the feedback.
We can achieve this by combining HTML5's validation state with React's ability to conditionally render elements. Every input element has a validity property in the DOM, which we can check. Additionally, CSS provides pseudo-classes like :invalid that we can use to style inputs based on their validity.
To create a good user experience, we don't want to show an error message the moment the user starts typing. A common pattern is to show the validation message only after the user has interacted with a field and then moved away (the onBlur event).
BEST Ways to Handle and Validate React Forms without a Library
Let's watch a demonstration of how to implement this 'from scratch' validation. This video by Lama Dev shows how to use HTML5 attributes for the rules and then adds custom logic to control when error messages are displayed.
Please watch these two key segments: Using HTML5 Attributes (27:23 - 32:46): Pay attention to how required, type="email", and pattern are added directly to the input definitions to enforce rules. Providing Custom Feedback (33:47 - 39:38): This is the crucial part. Observe how an onBlur event is used to track which fields have been 'touched' and how this state, combined with CSS, is used to conditionally display custom error messages and apply a red border. This is a great example of 'clear user feedback'.
This approach is lightweight and excellent for simple forms. However, as validation logic grows more complex (e.g., cross-field dependencies like "password must match confirm password"), managing it manually can become cumbersome.
2. The Production-Grade Approach: React Hook Form & Zod
For complex applications, developers typically turn to specialized libraries. We'll explore a powerful and very popular combination:
- React Hook Form: A performant, flexible library for managing form state and submission. It minimizes re-renders by default.
- Zod: A TypeScript-first schema declaration and validation library. It allows you to define a "schema"—a definitive source of truth for your data's shape and rules.
This approach separates the "what" (the validation rules, defined in a Zod schema) from the "how" (the form's UI and state management, handled by React Hook Form).
2.1. Defining the Rules with a Zod Schema
With Zod, you create an object that describes your form's data structure and the constraints on each field. This declarative style is highly readable and maintainable.
Because Zod is TypeScript-first, it can automatically infer a TypeScript type from your schema. This means you only have to define your data structure once, and you get both runtime validation and static type safety for free.
Handling Complex Validation Scenarios with Zod
This article from the Strapi blog provides a clear, text-based explanation of how to build a complex validation schema with Zod. It's a great reference for the available validation methods.
Please read the section titled 'Handling Complex Validation Scenarios with Zod'. Note how different methods like .min(), .max(), .email(), and .regex() are chained together to build up the rules for each field. Pay special attention to the .refine() example for the age field, which shows how to implement completely custom validation logic.
To see this in action, particularly for a common and important use case—cross-field validation—let's turn to a video example.
React Hook Form with ZOD Tutorial - React and Typescript Form Validation Tutorial
This video by PedroTech demonstrates building a Zod schema live. It's a great way to see the concepts from the article applied, including a more advanced use of .refine().
Watch the segment from 07:56 to 13:17. The key part here is the implementation of the password confirmation check. Notice how .refine() is applied to the entire schema object, giving it access to all form fields (data) to compare data.password with data.confirmPassword. This is a powerful pattern for rules that depend on multiple fields.
2.2. Connecting the Schema to the Form
Once we have our Zod schema, we need to integrate it into our React component. This is where React Hook Form comes in.
The core hook is useForm(). We provide our Zod schema to it via a special "resolver" package (@hookform/resolvers/zod). The hook then gives us back everything we need to manage the form:
register: A function to connect each<input>to its corresponding field in the schema.handleSubmit: A wrapper for our submission function that first runs the validation. It will only call our function if all rules in the Zod schema pass.formState: { errors }: An object containing any validation errors. This is what we'll use to provide user feedback.
React Hook Form with ZOD Tutorial - React and Typescript Form Validation Tutorial
Let's continue with the PedroTech video to see how to wire everything together and display the error messages.
Please watch these two segments: Connecting the Form (13:17 - 19:56): See how useForm is initialized with the zodResolver and the schema. Observe the use of the register function to link inputs to the form state. The presenter also fixes a common bug with number inputs, which is a useful tip (valueAsNumber: true). Displaying Errors (21:53 - 24:53): This part directly addresses our goal. Notice how the errors object from formState is used. For each field, there's a conditional render: errors.fieldName && <p>{errors.fieldName.message}</p>. The error messages are the custom strings we defined in our Zod schema.
This library-based approach provides a robust, scalable, and type-safe foundation for handling any form, no matter how complex its validation requirements are.
Test your understanding!
Imagine you are using the Zod and React Hook Form setup we just learned. You need to add a "Terms of Service" checkbox to your form. This checkbox must be checked for the form to be valid.
How would you modify the Zod schema to add this validation rule?
// The new field is named 'termsAccepted'
const FormSchema = z.object({
//... existing fields like username, email
// How would you define the rule for termsAccepted?
});
Show answer
There are a couple of great ways to do this.
Option 1 (Strict):
The most direct way is to assert that the value must be the literal true.
const FormSchema = z.object({
//...
termsAccepted: z.literal(true, {
errorMap: () => ({ message: "You must accept the terms of service." }),
}),
});
This works because an unchecked checkbox will have a value of false, failing the validation.
Option 2 (More flexible, using .refine()):
You could also define it as a boolean and then use .refine() to ensure it's true.
const FormSchema = z.object({
//...
termsAccepted: z.boolean().refine(val => val === true, {
message: "You must accept the terms of service."
})
});
Both achieve the same goal. The z.literal(true) approach is slightly more idiomatic for this specific "must be checked" scenario in Zod.
Conclusion
Today we've armed you with two powerful methods for form validation. You can now ensure data integrity on the client side and provide a much better experience for your users.
Key Takeaways:
- Client-side validation prevents invalid data from being submitted, saving server resources and providing instant feedback.
- The HTML5 approach is great for simple forms, using attributes like
requiredandpattern. Good UX involves usingonBlurand custom styling to control when and how errors are shown. - For complex, production applications, the combination of React Hook Form and Zod is a superior solution.
- Zod provides a single source of truth for your data's shape and rules, giving you both runtime validation and static TypeScript types.
- React Hook Form connects your Zod schema to the UI, manages form state efficiently, and provides a simple
errorsobject to display feedback.
In our next lesson, we'll tackle what happens after successful validation: Manage asynchronous form submissions, including loading and error states. We'll learn how to give users feedback while we're communicating with a server, such as showing a loading spinner and handling any errors that the server might send back.