🧘♂️ Simple form
The simple way to validate forms in your fullstack app.
Installation
Simple form is an Astro integration. You can install and configure this via the Astro CLI using astro add
:
After installing, you’ll need to add a type definition to your environment for editor hints. Add this reference to a new or existing src/env.d.ts
file:
Simple form can be used with any framework. You can install it via npm:
Create a validated form
Type: createForm(ZodRawShape): { inputProps: Record<string, InputProps>, validator: ZodRawShape }
You can create a simple form with the createForm()
function. This lets you specify a validation schema using Zod, where each input corresponds to an object key. Simple form supports string, number, or boolean (checkbox) fields.
createForm()
returns both a validator and the inputProps
object. inputProps
converts each key of your validator to matching HTML props / attributes. The following props are generated today:
name
- the object key.type
-checkbox
for booleans,number
for numbers, andtext
for strings.aria-required
-true
by default,false
when.optional()
is used. Notearia-required
is used to add semantic meaning for screenreaders, but leave room to add a custom error banner.
Our signupForm
example generates the following inputProps
object:
Handle array values
You may want to submit multiple form values under the same name. This is common for multi-select file inputs, or generated inputs like “add a second contact.”
You can aggregate values under the same name using z.array()
in your validator:
Now, all inputs with the name contactNames
will be aggregated. This uses FormData.getAll()
behind the scenes:
Note that fieldErrors
can be retrieved by index. For example, to get parse errors for the second input, use fieldErrors.contactNames[1]
.
Sanitize User Input
You may need to sanitize user input with rich text content. This is important for any text rendered as HTML to prevent Cross-Site Scripting (XSS) attacks. You can use the sanitize-html library for this:
Next, call sanitize-html
from your text validator with a Zod transform()
:
You can find a sanitization example in our Astro playground