DEV Community

Cover image for πŸš€ Day 9 of Learning React: Why Every Form Needs Validation (React Hook Form Made It Surprisingly Easy)
Bismay.exe
Bismay.exe

Posted on

πŸš€ Day 9 of Learning React: Why Every Form Needs Validation (React Hook Form Made It Surprisingly Easy)

πŸ“Œ Missed Day 8? I explored why React doesn't usually let us work directly with the DOM, how useRef() gives us access to real DOM elements, and why React Hook Form makes handling forms much cleaner. You can **read it here* and then come back. I'll wait. β˜•οΈ*


Yesterday, I finally understood how React Hook Form simplified form handling.

I thought that was the hard part.

Turns out...

Building the form was only half the job.

Because no matter how beautiful a form looks, there's always one problem.

Users can type literally anything.

An empty name.

An invalid email.

A phone number with only five digits.

Without validation, my application would happily accept all of them.

Today's lesson wasn't about making forms prettier.

It was about making them smarter.

Let's dive in. πŸš€


🧠 Quick Recap

Yesterday's big question was:

Why doesn't React use the DOM directly?

Here's what I learned on Day 8:

  • 🎣 useRef() lets React keep references to DOM elements.
  • 🌳 React usually works with the Virtual DOM instead of the Real DOM.
  • πŸ“ React Hook Form makes handling forms much cleaner.
  • πŸš€ register(), handleSubmit(), and reset() reduce repetitive form logic.

Today we're answering a different question:

How do we stop users from submitting invalid data? πŸ€”


πŸ€” A Form That Accepts Everything...

At first, my form looked perfectly fine.

<input {...register("name")} />
<input {...register("email")} />
Enter fullscreen mode Exit fullscreen mode

Users could type...

Click Submit...

Everything worked.

Or at least...

It looked like it worked.

Then I started thinking about something.

React Hook Form before validation

The form before submission. At this point, nothing prevents users from entering invalid data.

What if someone submitted this?

Name:
"          "
Enter fullscreen mode Exit fullscreen mode

Or this?

Email:
abc123
Enter fullscreen mode Exit fullscreen mode

Or even left every field empty?

My form would still accept it.

That's when I realized something.

Collecting user input is easy. Trusting it is the difficult part.


🚫 My First Validation Rule

The first validation rule I added was surprisingly simple.

register("name", {
  required: "Name is required",
})
Enter fullscreen mode Exit fullscreen mode

That one line completely changed the form.

If I clicked Submit without entering a name...

React Hook Form immediately displayed:

Name is required
Enter fullscreen mode Exit fullscreen mode

And something interesting happened.

My formSubmit() function never ran.

Instead of giving me invalid data...

React Hook Form stopped everything before submission.

React Hook Form validation errors

Validation errors appear before the form is submitted, preventing invalid data from reaching my submit function.

That felt really impressive.


πŸ“§ Making Sure Emails Actually Look Like Emails

The next field was email.

register("email", {
  required: "Email is required",
  pattern: {
    value: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
    message: "Please enter valid email",
  },
})
Enter fullscreen mode Exit fullscreen mode

The regular expression looked scary at first. πŸ˜…

I definitely wasn't trying to memorize it.

What mattered to me was understanding its job.

If the entered email doesn't match the expected format...

React Hook Form simply refuses to submit the form and shows my custom error message.

That made much more sense than manually checking every possible email format myself.


πŸ“± Validating a Phone Number

Next came the mobile number.

register("mobile", {
  required: "Mobile is required",
  minLength: {
    value: 10,
    message: "Minimum 10 digits are required",
  },
  maxLength: {
    value: 10,
    message: "Maximum 10 digits are required",
  },
})
Enter fullscreen mode Exit fullscreen mode

This one was interesting.

Using both minLength and maxLength meant the user had to enter exactly 10 digits.

Less than ten?

Error.

More than ten?

Still an error.

It was a simple way to enforce a rule without writing any custom logic.


πŸ–ΌοΈ Even the Image Field Needed Validation

The image input looked straightforward.

register("image", {
  required: "Image is required",
})
Enter fullscreen mode Exit fullscreen mode

Without it...

Someone could submit the form without providing an image.

The validation rule made sure every user card had all the information it needed before being created.


🚨 The errors Object Did All the Heavy Lifting

One thing I really liked was how React Hook Form keeps track of every validation error.

Displaying an error was as simple as:

{errors.name && (
  <p>{errors.name.message}</p>
)}
Enter fullscreen mode Exit fullscreen mode

The same pattern worked for every field.

errors.email
errors.mobile
errors.image
Enter fullscreen mode Exit fullscreen mode

That was much cleaner than writing lots of if statements myself.

I didn't need to manually check:

if (name === "") {
  ...
}
Enter fullscreen mode Exit fullscreen mode

or

if (email === "") {
  ...
}
Enter fullscreen mode Exit fullscreen mode

React Hook Form had already done that work for me.

I only needed to decide how the errors should appear on the screen.


πŸ“€ Validation Happens Before Submission

One thing finally clicked today.

I used to think clicking Submit immediately called my function.

That's not actually what happens.

The flow looks more like this.

User Clicks Submit
          ↓
React Hook Form Checks Every Rule
          ↓
Everything Valid?

YES βœ…
Run formSubmit()

NO ❌
Fill the errors Object
Display Error Messages
Enter fullscreen mode Exit fullscreen mode

That small flow completely changed how I think about forms.


πŸ’‘ My Mental Model

Here's how I visualize today's lesson now.

User Types
      ↓
Validation Rules
      ↓
Valid Input?
      ↓
YES βœ… --------β†’ Submit Form
      ↓
NO ❌ --------β†’ Show Errors
Enter fullscreen mode Exit fullscreen mode

Instead of blindly accepting everything...

The form now protects itself before any data is submitted.


πŸ’‘ My Biggest Takeaways Today

  • πŸ“ Building a form is only half the jobβ€”validation is just as important.
  • 🚫 required prevents empty submissions.
  • πŸ“§ pattern helps validate formats like email addresses.
  • πŸ“± minLength and maxLength can enforce rules such as a 10-digit phone number.
  • 🚨 React Hook Form automatically stores validation errors inside the errors object.
  • ⚑ Validation happens before the submit function is executed.

πŸ“š Learning Source

I'm currently learning React through the React Cohort 3.0 by Devendra Dhote at Sheriyans Coding School.

This article isn't a copy of the course.

It's my personal understanding after today's class, rewritten entirely in my own words.

Writing these articles helps me reinforce what I've learned, and hopefully helps other beginners who are on the same journey. 🀝

If I've misunderstood something, I'd genuinely appreciate your corrections in the comments. 😊


πŸ™Œ Final Thoughts

Yesterday, I learned how React Hook Form made building forms easier.

Today, I learned that forms aren't just about collecting data.

They're also responsible for protecting it.

That shift completely changed how I look at forms.

Instead of thinking:

Collect Input
      ↓
Submit
Enter fullscreen mode Exit fullscreen mode

I now think:

Collect Input
      ↓
Validate Input
      ↓
Submit
Enter fullscreen mode Exit fullscreen mode

It seems like a small difference.

But today's project showed me that validation isn't an extra feature.

It's part of building a reliable application.

See you on Day 10! πŸš€


πŸ’¬ When you first started building forms, did you add validation from the beginning, or did you realize its importance only after seeing users enter unexpected data? I'd love to hear your experience in the comments. 😊

I'd love to hear your experience in the comments. 😊

If you're following along with this series, you can also find me on GitHub, where I'll be sharing my projects and documenting my progress.

Bismay-exe (Bismay.exe) Β· GitHub

πŸ‘‹ Hi, I’m Bismay πŸ’» Developer passionate about building clean, minimal, and elegant apps πŸš€ Focused on coding 🌱 Always learning, creating & new ideas - Bismay-exe

favicon github.com

πŸ€– AI Disclosure: This article is based on my own React learning journey, class notes, code experiments, and understanding. I used ChatGPT to help improve the writing, structure, and readability of this post. I reviewed and verified the technical explanations before publishing, and I take responsibility for everything shared here.

Thanks for reading! πŸš€


Top comments (0)