Skip to content

Commit f0d5019

Browse files
committed
docs: add arrays to README
1 parent 9b8ebb7 commit f0d5019

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

packages/form/README.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,49 @@ signupForm.inputProps;
8989
*/
9090
```
9191

92+
### Handle array values
93+
94+
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."
95+
96+
You can aggregate values under the same name using `z.array()` in your validator:
97+
98+
```ts
99+
import { createForm } from "simple:form";
100+
import z from "zod";
101+
102+
const contact = createForm({
103+
contactNames: z.array(z.string()),
104+
});
105+
```
106+
107+
Now, all inputs with the name `contactNames` will be aggregated. This [uses `FormData.getAll()`](https://developer.mozilla.org/en-US/docs/Web/API/FormData/getAll) behind the scenes:
108+
109+
```astro
110+
---
111+
import { createForm } from "simple:form";
112+
import z from "zod";
113+
114+
const contact = createForm({
115+
contactNames: z.array(z.string()),
116+
});
117+
118+
const res = await Astro.locals.form.getData(contact);
119+
console.log(res?.data);
120+
// contactNames: ["Ben", "George"]
121+
---
122+
123+
<form method="POST">
124+
<label for="contact-1">Contact 1</label>
125+
<input id="contact-1" {...contact.inputProps.contactNames} />
126+
{res.fieldErrors?.contactNames?.[0]}
127+
<label for="contact-2">Contact 2</label>
128+
<input id="contact-2" {...contact.inputProps.contactNames} />
129+
{res.fieldErrors?.contactNames?.[1]}
130+
</form>
131+
```
132+
133+
Note that `fieldErrors` can be retrieved by index. For example, to get parse errors for the second input, use `fieldErrors.contactNames[1]`.
134+
92135
### Parse form requests
93136

94137
You can parse form requests from your Astro component frontmatter. Simple form exposes helpers to parse and validate these requests with the [`Astro.locals.form`](https://docs.astro.build/en/reference/api-reference/#astrolocals) object.

0 commit comments

Comments
 (0)