Overview
Express Zod API supports traditional HTML form submissions using theapplication/x-www-form-urlencoded content type. This is useful for accepting data from standard HTML forms without JavaScript or for APIs that need to support form-based workflows.
Using ez.form()
Use the proprietaryez.form() schema to describe form input:
Configuration
Forms are parsed using theformParser configuration option, which defaults to express.urlencoded():
Content Type Requirement
Using Custom z.object()
You can also use a regularz.object() with form fields:
Complete Form Example
HTML Form Example
Here’s how to create an HTML form that submits to this endpoint:Form Validation
Required Fields
Optional Fields
Default Values
Custom Validation
Arrays in Forms
Checkboxes
Single Checkbox
Multiple Checkboxes
Radio Buttons
Select Dropdowns
Handling Extra Fields
To accept unlisted extra fields, usepassthrough():
Authentication Forms
CSRF Protection
Implement CSRF protection for forms:File Uploads with Forms
For file uploads, use
multipart/form-data instead. See File Uploads for details.Client-Side JavaScript Submission
Best Practices
Validate on Both Sides
Validate on Both Sides
Always validate on both client (HTML5 validation) and server (Zod schemas) for security and user experience.
Use Appropriate Field Types
Use Appropriate Field Types
Use specific HTML input types (
email, url, tel, etc.) to improve mobile UX and enable browser validation.Provide Clear Error Messages
Provide Clear Error Messages
Use Zod’s custom error messages to provide user-friendly feedback when validation fails.
Handle Empty Strings
Handle Empty Strings
HTML forms send empty strings for blank fields. Use
.min(1) to require non-empty values or .optional() for truly optional fields.Related Topics
- File Uploads - Using multipart/form-data for files
- Input Sources - Customizing input sources
- Validation - Schema validation concepts