Astro Actions validation happens in the action’s input schema: declare each field’s rules with Zod (imported from astro/zod), and Astro checks the submitted form before your handler runs. When validation fails, the result’s error passes isInputError(error), and error.fields holds an array of messages for each field name, which you render next to the matching input. The form works without JavaScript and keeps working when you add it.
Key Takeaways
- Put validation rules in
input: z.object({...}); the handler only runs with valid data.- Use
accept: 'form'so Astro convertsFormDatato the shape your schema expects, including numbers and booleans.Astro.getActionResult()returns the result after a plain HTML form post;isInputError()narrows it to field errors.- Cross-field rules use
.refine()with apath, so the error lands on the right field.
Define the action
// src/actions/index.ts
import { defineAction } from 'astro:actions';
import { z } from 'astro/zod';
export const server = {
signup: defineAction({
accept: 'form',
input: z
.object({
name: z.string().trim().min(2, 'Enter your name'),
email: z.email('Enter a valid email address'),
age: z.number().int().min(18, 'You must be 18 or older'),
password: z.string().min(12, 'Use at least 12 characters'),
confirm: z.string(),
terms: z.boolean().refine((v) => v, 'Please accept the terms'),
})
.refine((d) => d.password === d.confirm, {
path: ['confirm'],
error: 'Passwords do not match',
}),
handler: async ({ name, email }) => {
// ...create the account
return { name, email };
},
}),
};
With accept: 'form', Astro reads the schema to convert form strings: age becomes a number, and terms becomes true when the checkbox is ticked and false when it is missing. Messages passed as the second argument become the text users see. Actions need on-demand rendering and an adapter; the server output fix covers that error.
Render errors next to fields
---
// src/pages/signup.astro
import { actions, isInputError } from 'astro:actions';
export const prerender = false;
const result = Astro.getActionResult(actions.signup);
const fieldErrors = isInputError(result?.error) ? result.error.fields : {};
const generalError = result?.error && !isInputError(result.error) ? result.error.message : null;
---
{result?.data && <p role="status">Welcome, {result.data.name}.</p>}
{generalError && <p role="alert">{generalError}</p>}
<form method="POST" action={actions.signup} novalidate>
<label for="email">Email</label>
<input id="email" name="email" type="email" aria-invalid={fieldErrors.email ? 'true' : undefined} aria-describedby="email-error" />
{fieldErrors.email && <p id="email-error" class="error">{fieldErrors.email.join(' ')}</p>}
<label for="confirm">Confirm password</label>
<input id="confirm" name="confirm" type="password" aria-describedby="confirm-error" />
{fieldErrors.confirm && <p id="confirm-error" class="error">{fieldErrors.confirm.join(' ')}</p>}
<label><input name="terms" type="checkbox" value="true" /> I accept the terms</label>
{fieldErrors.terms && <p class="error">{fieldErrors.terms.join(' ')}</p>}
<button type="submit">Create account</button>
</form>
The other fields follow the same pattern. action={actions.signup} posts the form to the action, Astro renders the page as the response to that POST, and getActionResult() holds either data or error. aria-invalid and aria-describedby let screen readers announce each error with its field. novalidate turns off the browser’s own checks so you can see the server errors while testing; remove it in production to keep both layers.
Keeping typed values
After a plain form post, the re-rendered inputs are empty unless you set their value; only the action result is handed to the page. For short forms that is acceptable, since the errors tell people what to fix. For longer forms, submit with JavaScript as shown next so nothing is lost, or use getActionContext() in middleware to store the result in a session and redirect, as the official Actions guide describes. Never refill password fields either way.
Validate with JavaScript enabled
The same action works from a script, returning { data, error } without a page reload:
<script>
import { actions, isInputError } from 'astro:actions';
const form = document.querySelector('form')!;
form.addEventListener('submit', async (e) => {
e.preventDefault();
const { data, error } = await actions.signup(new FormData(form));
if (isInputError(error)) {
console.log(error.fields); // { email: ['Enter a valid email address'], ... }
} else if (data) {
form.replaceWith(`Welcome, ${data.name}.`);
}
});
</script>
Server validation still runs; the browser only changes how you display the result. Our Astro Actions guide covers redirects, ActionError codes and calling actions from server code. Starting from one of our Astro themes? Their contact forms are static HTML, and this pattern drops in once you add an adapter.
FAQ
How do I validate form input in Astro Actions?
Define a Zod schema in the action’s input option and set accept: 'form'. Astro validates the submitted data before calling the handler and returns an input error if any rule fails.
How do I show field-level errors from an Astro Action?
Get the result with Astro.getActionResult(actions.name) or from the client call, check isInputError(result.error), and render result.error.fields.fieldName, which is an array of messages.
Where do I import z from for Astro Actions?
Import z from astro/zod. The z export from astro:content is deprecated, and Astro 7 uses Zod 4.
How do I validate that two fields match?
Add .refine() to the object schema with a check comparing both fields and path: ['confirm'], so the error appears under the confirm field.