การตรวจสอบความถูกต้องและการจัดการข้อผิดพลาดในการกระทำฝั่งเซิร์ฟเวอร์
สร้างการกระทำฝั่งเซิร์ฟเวอร์ที่แข็งแกร่งด้วยการตรวจสอบความถูกต้องของข้อมูลนำเข้าด้วย Zod ส่งคืนสถานะข้อผิดพลาดแบบมีโครงสร้าง และแสดงสถานะเหล่านั้นในแบบฟอร์มด้วย useActionState
การตรวจสอบความถูกต้องและการจัดการข้อผิดพลาดในการกระทำฝั่งเซิร์ฟเวอร์ เป็นบทเรียน Next.js 15 Fullstack (App Router + Server Actions) ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 3 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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.
เรียนรู้ TypeScript ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 22
- บทเรียน
- 88
คำถามที่พบบ่อย
บทเรียน “การตรวจสอบความถูกต้องและการจัดการข้อผิดพลาดในการกระทำฝั่งเซิร์ฟเวอร์” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การตรวจสอบความถูกต้องและการจัดการข้อผิดพลาดในการกระทำฝั่งเซิร์ฟเวอร์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส 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 ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Next.js 15 Fullstack (App Router + Server Actions) หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Next.js 15 Fullstack (App Router + Server Actions) บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 3 บทเรียน
บทเรียน “การตรวจสอบความถูกต้องและการจัดการข้อผิดพลาดในการกระทำฝั่งเซิร์ฟเวอร์” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Next.js 15 Fullstack (App Router + Server Actions) นี้ได้ไหม
ได้ บทเรียน Next.js 15 Fullstack (App Router + Server Actions) ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การอัปเดต UI แบบมองในแง่ดี
- การอัปโหลดไฟล์ด้วยแอ็กชัน
- การตรวจสอบความถูกต้องและการจัดการข้อผิดพลาดในการกระทำฝั่งเซิร์ฟเวอร์