0Pricing
Next.js 15 Fullstack Web Apps · บทเรียน

การตรวจสอบแบบฟอร์มด้วย React Hook Form

นำการตรวจสอบแบบฟอร์มที่มีประสิทธิภาพมาใช้ด้วยไลบรารี React Hook Form ยอดนิยม

การตรวจสอบแบบฟอร์มด้วย React Hook Form เป็นบทเรียน Next.js 15 Fullstack Web Apps ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Next.js 15 Fullstack Web Apps และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Next.js 15 Fullstack Web Apps มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why React Hook Form?

Managing forms in React can get complex, especially with validation. React Hook Form (RHF) is a popular library designed to simplify this process.

  • Performance: Minimizes unnecessary re-renders.
  • Developer Experience: Simple API, easy to integrate.
  • Validation: Powerful and flexible rules.

It helps you build robust forms with less code and better performance.

Getting Started: useForm

First, install React Hook Form using npm or yarn. Then, import and use the useForm hook in your component. This hook initializes your form and provides essential methods.

import React from 'react';
import { useForm } from 'react-hook-form';

function SimpleForm() {
  // useForm initializes the form and gives us tools
  const { register, handleSubmit } = useForm();

  // This function runs when the form is submitted
  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {/* Inputs will go here */}
      <button type="submit">Submit</button>
    </form>
  );
}

Registering Input Fields

To make an input field part of your RHF form, you need to "register" it. The register function takes the input's name and returns props that you spread onto the input element.

import React from 'react';
import { useForm } from 'react-hook-form';

function RegisterInputForm() {
  const { register, handleSubmit } = useForm();
  const onSubmit = (data) => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label htmlFor="name">Name:</label>
      <input id="name" {...register("name")} />
      <br/>
      <label htmlFor="email">Email:</label>
      <input id="email" type="email" {...register("email")} />
      <br/>
      <button type="submit">Submit</button>
    </form>
  );
}

Basic Validation: Required

RHF lets you easily add validation rules during registration. The required: true option makes an input field mandatory. If left empty, the form won't submit.

import React from 'react';
import { useForm } from 'react-hook-form';

function RequiredValidationForm() {
  const { register, handleSubmit } = useForm();
  const onSubmit = (data) => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label htmlFor="itemName">Item Name:</label>
      <input id="itemName" {...register("itemName", { required: true })} />
      <br/>
      <button type="submit">Submit</button>
    </form>
  );
}

Displaying Error Messages

When validation fails, RHF populates the formState.errors object. You can use this object to display helpful error messages next to your input fields, guiding the user.

import React from 'react';
import { useForm } from 'react-hook-form';

function DisplayErrorsForm() {
  const { register, handleSubmit, formState: { errors } } = useForm();
  const onSubmit = (data) => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label htmlFor="name">Name:</label>
      <input id="name" {...register("name", { required: "Name is required!" })} />
      {errors.name && <p style={{color: 'red'}}>{errors.name.message}</p>}
      <br/>
      <label htmlFor="age">Age:</label>
      <input id="age" type="number" {...register("age", { min: 18 })} />
      {errors.age && <p style={{color: 'red'}}>Must be at least 18.</p>}
      <br/>
      <button type="submit">Submit</button>
    </form>
  );
}

Length & Pattern Rules

RHF also offers minLength and maxLength for character limits. The pattern option allows you to validate input against a regular expression, perfect for specific formats like email or phone numbers.

import React from 'react';
import { useForm } from 'react-hook-form';

function LengthPatternForm() {
  const { register, handleSubmit, formState: { errors } } = useForm();
  const onSubmit = (data) => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label htmlFor="username">Username:</label>
      <input id="username" {...register("username", { minLength: 3, maxLength: 10 })} />
      {errors.username && <p style={{color: 'red'}}>3-10 chars.</p>}
      <br/>
      <label htmlFor="email">Email:</label>
      <input id="email" type="email"
        {...register("email", {
          pattern: /^\S+@\S+$/i
        })}
      />
      {errors.email && <p style={{color: 'red'}}>Invalid email.</p>}
      <br/>
      <button type="submit">Submit</button>
    </form>
  );
}

Custom Validation Logic

When built-in rules aren't enough, you can create custom validation logic using the validate option in register. This function should return true for valid input or a string error message otherwise.

import React from 'react';
import { useForm } from 'react-hook-form';

function CustomValidationForm() {
  const { register, handleSubmit, formState: { errors } } = useForm();
  const onSubmit = (data) => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label htmlFor="password">Password:</label>
      <input id="password" type="password"
        {...register("password", {
          validate: (value) =>
            value.length >= 8 || "Min 8 chars!"
        })}
      />
      {errors.password && <p style={{color: 'red'}}>{errors.password.message}</p>}
      <br/>
      <button type="submit">Submit</button>
    </form>
  );
}

Handling Form Submission

The handleSubmit function from useForm wraps your own submission logic. It ensures your onSubmit function is only called if all form validations pass. It automatically passes the validated form data to your function.

import React from 'react';
import { useForm } from 'react-hook-form';

function SubmitHandlerForm() {
  const { register, handleSubmit, formState: { errors } } = useForm();

  // This function is called only if validation passes
  const onSubmit = (data) => {
    console.log("Form data:", data);
    alert("Form submitted successfully!");
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label htmlFor="task">Task Description:</label>
      <input id="task" {...register("task", { required: true })} />
      {errors.task && <p style={{color: 'red'}}>Task is required.</p>}
      <br/>
      <button type="submit">Add Task</button>
    </form>
  );
}

Resetting Form Fields

After a successful submission, or if you want to clear the form at any point, the reset method from useForm is very useful. It can clear all fields or set them to specific default values.

import React from 'react';
import { useForm } from 'react-hook-form';

function ResetForm() {
  const { register, handleSubmit, reset } = useForm();

  const onSubmit = (data) => {
    console.log(data);
    alert("Data sent!");
    reset(); // Clears all form fields
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label htmlFor="feedback">Your Feedback:</label>
      <input id="feedback" {...register("feedback")} />
      <br/>
      <button type="submit">Send Feedback</button>
      <button type="button" onClick={() => reset()}>Clear Form</button>
    </form>
  );
}

Test Your RHF Knowledge

Which of the following are valid ways to define validation rules when registering an input with React Hook Form?

Recap: RHF for Validation

You've learned how React Hook Form simplifies form validation in Next.js applications!

  • It provides the useForm hook to manage your form.
  • Inputs are connected using the register method.
  • Validation rules (like required, minLength, pattern, validate) are passed directly to register.
  • Errors are accessed via formState.errors.
  • The handleSubmit function ensures your data is valid before submission.
  • The reset method helps clear forms easily.

Next, explore how to combine these with Server Actions for fullstack form management!

คำถามที่พบบ่อย

บทเรียน “การตรวจสอบแบบฟอร์มด้วย React Hook Form” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การตรวจสอบแบบฟอร์มด้วย React Hook Form” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Next.js 15 Fullstack Web Apps ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Next.js 15 Fullstack Web Apps มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การตรวจสอบแบบฟอร์มด้วย React Hook Form”

นำการตรวจสอบแบบฟอร์มที่มีประสิทธิภาพมาใช้ด้วยไลบรารี React Hook Form ยอดนิยม คุณปฏิบัติ Next.js 15 Fullstack Web Apps ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Next.js 15 Fullstack Web Apps หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Next.js 15 Fullstack Web Apps บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “การตรวจสอบแบบฟอร์มด้วย React Hook Form” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Next.js 15 Fullstack Web Apps นี้ได้ไหม

ได้ บทเรียน Next.js 15 Fullstack Web Apps ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. คอมโพเนนต์ควบคุมและสถานะ
  2. การตรวจสอบแบบฟอร์มด้วย React Hook Form
  3. แบบฟอร์มฟูลสแตกด้วยการดำเนินการเซิร์ฟเวอร์
  4. การอัปโหลดไฟล์และการจัดการฟอร์มแบบหลายส่วน
← กลับไปที่ Next.js 15 Fullstack Web Apps