Server Actions
Server Action Form Validation
This example was originally created as one of several examples I wrote for a post about Using Server Actions with Next JS. See that post for a more detailed explanation of the concepts here.
We usually need to perform some kind of validation on the data that users submit in forms. Zod is a popular library for this purpose, and it can be used in conjunction with Server Actions to validate form data before it is submitted.
Live Demo
Try submitting the live form below with or without entering text in the various fields. The form uses Zod on the server-side to validate input, and will surface per-field validation error messages if present:
Code
Here's a simple Zod schema that we can use to validate a form that collects information about a device. The schema defines the fields that the form will have, and the validation rules for each field:
Our server action in this case looks like this:
The action just takes data from the form, pulls out the fields we care about, and then validates it using the Zod schema. If the data is valid, it creates a device and returns a success message. If the data is invalid, it returns a validation error message with the issues that Zod found. These can then be shown in the form:
This particular form has a few helper functions to make it easier to show validation errors - check out form.tsx source for the full implementation.
Authentication doesn't happen automagically
This is a very simple example, but in a real-world application you would likely want to add some kind of authentication to your server actions. These server action endpoints are as wide open as any other, so you need to reason about them in the exact same way when it comes to authentication and authorization.