Actions and forms
Validate FormData
Convert unknown form values into a trusted shape and return field-level errors instead of assuming TypeScript checked runtime input.
8 minute lesson
formData.get() can return a string, a File, or null. Type annotations do not validate any of those runtime values.
Normalize the input, validate required fields and bounds, and return a serializable result for expected errors. A schema library is useful in a larger form, but the important boundary is the same: do not perform the write until server-side validation succeeds.
Authentication answers who made the request; validation answers whether the submitted shape is acceptable; authorization answers whether that person may perform this operation. Run all three before the write. Client constraints improve feedback but can be removed or bypassed.
const rawTitle = formData.get('title')
if (typeof rawTitle !== 'string' || rawTitle.trim().length < 3) {
return { errors: { title: 'Use at least 3 characters' } }
}
const title = rawTitle.trim()
Do not echo raw values or internal exception messages in the returned state. Preserve safe user-entered values separately when the form should be repopulated, and use a general message for an unexpected storage failure.
Reject missing, File, whitespace-only, too-short, and very long titles by constructing FormData directly in a small test. Confirm each expected problem returns a field message and performs no write.
Lesson completed