Validate a Server Action
Medium · Server Actions
A **Server Action** is an async function that runs on the server. A file that starts with "use server" turns its exports into actions you can pass to <form action={...}>. When used with useActionState, the action receives the previous state and the submitted FormData, and whatever it returns becomes the new state shown by the form.
Always validate on the server: anyone can send a request to your action, even without your form.
Implement createTodo(prevState, formData):
- title = formData.get("title") trimmed (a missing field counts as empty).
- Empty: error "Title is required".
- More than 40 characters: error "Title must be 40 characters or less".
- dueDate is optional. If it is present and not empty, it must be YYYY-MM-DD (/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/) **and** a real calendar day (2026-02-30 is not). Otherwise error "Enter a valid date".
- If there are errors, return { errors } with only the failing fields (title and/or dueDate).
- Otherwise return { message: 'Created "<title>"' } with the trimmed title.
Tip: new Date(value + "T00:00:00Z").toISOString().slice(0, 10) === value is only true for real days (check for Invalid Date first).
The driver submitForm(fields) is already written.
Next: Theme Cookie Route