使用 React Hook Form 进行表单验证
使用热门的 React Hook Form 库实现高效的表单验证。
使用 React Hook Form 进行表单验证 是 CoddyKit 上的免费 Next.js 15 Fullstack Web Apps 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 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
useFormhook to manage your form. - Inputs are connected using the
registermethod. - Validation rules (like
required,minLength,pattern,validate) are passed directly toregister. - Errors are accessed via
formState.errors. - The
handleSubmitfunction ensures your data is valid before submission. - The
resetmethod helps clear forms easily.
Next, explore how to combine these with Server Actions for fullstack form management!
常见问题解答
「使用 React Hook Form 进行表单验证」课时是免费的吗?
是的 — 「使用 React Hook Form 进行表单验证」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 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 导师会在你学习这节课的过程中回答你的问题。
学习 Next.js 15 Fullstack Web Apps 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack Web Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「使用 React Hook Form 进行表单验证」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Next.js 15 Fullstack Web Apps 课中编写并运行代码吗?
能。每节 Next.js 15 Fullstack Web Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 受控组件与状态
- 使用 React Hook Form 进行表单验证
- 使用服务器操作构建全栈表单
- 文件上传与多部分表单处理