服务器操作中的验证与错误处理
使用 Zod 验证输入、返回结构化错误状态,并通过 useActionState 在表单中呈现这些状态,构建稳健的服务器操作。
服务器操作中的验证与错误处理 是 CoddyKit 上的免费 Next.js 15 Fullstack (App Router + Server Actions) 课时。 这是第 3 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack (App Router + Server Actions) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 3 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Validate Server Actions?
Server Actions receive data straight from the client, which can never be trusted. Validation guards against malformed input, injection, and broken business rules before anything touches your database.
Reading FormData
A Server Action bound to a form receives a FormData object. You read fields by name, but every value arrives as a string.
'use server';
export async function createPost(formData: FormData) {
const title = formData.get('title');
const views = formData.get('views');
}Defining a Zod Schema
Zod declares the shape and rules of your data. coerce converts string form values into the right types automatically.
import { z } from 'zod';
const PostSchema = z.object({
title: z.string().min(3, 'Title too short'),
views: z.coerce.number().int().min(0)
});Safe Parsing
Use safeParse instead of parse so validation failures return a result object rather than throwing. Inspect success to branch.
const parsed = PostSchema.safeParse({
title: formData.get('title'),
views: formData.get('views')
});
if (!parsed.success) {
// handle errors
}Returning a Structured Error State
Rather than throwing, return an object describing what went wrong. Field-level messages let the UI show errors next to the right input.
if (!parsed.success) {
return {
errors: parsed.error.flatten().fieldErrors,
message: 'Validation failed'
};
}Wiring useActionState
On the client, useActionState tracks the value your action returns. It gives you the latest state and a wrapped action to pass to the form.
'use client';
const [state, formAction] = useActionState(createPost, { errors: {} });Displaying Field Errors
Render messages from state.errors beneath each field so users see exactly what to fix.
<input name="title" />
{state.errors?.title && (
<p className="error">{state.errors.title[0]}</p>
)}Catching Unexpected Errors
Validation handles bad input, but database or network calls can still fail. Wrap them in try/catch and return a friendly message instead of leaking internals.
try {
await prisma.post.create({ data: parsed.data });
} catch (e) {
return { message: 'Database error. Please try again.' };
}Revalidating on Success
After a successful write, call revalidatePath so cached pages refetch and the new data appears immediately.
import { revalidatePath } from 'next/cache';
revalidatePath('/posts');
return { message: 'Post created!' };Never Trust the Client
Client-side validation improves UX but can be bypassed. Always re-validate on the server. The Server Action is your real security boundary.
Best Practices
Robust actions follow a pattern:
- Validate with Zod safeParse
- Return structured field errors
- Surface them with useActionState
- Wrap side effects in try/catch
- Revalidate on success
Quick Check
Test your validation knowledge.
Recap
You hardened your Server Actions:
- Validate
FormDatawith a Zod schema andsafeParse - Return structured
errorsand amessage - Track them with
useActionStateand render per field - Catch runtime failures and revalidate on success
Your forms now fail gracefully and stay secure.
用 AI 导师学习 TypeScript — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 22
- 课程
- 88
常见问题解答
「服务器操作中的验证与错误处理」课时是免费的吗?
是的 — 「服务器操作中的验证与错误处理」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack (App Router + Server Actions) 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 3 节课。
「服务器操作中的验证与错误处理」这节课中我会学到什么?
使用 Zod 验证输入、返回结构化错误状态,并通过 useActionState 在表单中呈现这些状态,构建稳健的服务器操作。 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack (App Router + Server Actions),全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Next.js 15 Fullstack (App Router + Server Actions) 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack (App Router + Server Actions) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 3 节。
「服务器操作中的验证与错误处理」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Next.js 15 Fullstack (App Router + Server Actions) 课中编写并运行代码吗?
能。每节 Next.js 15 Fullstack (App Router + Server Actions) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。