Build forms
@codeui/solid v0.3.0
Combine fields into a form with labels, descriptions, and validation.
This guide builds an export settings form with a required file name, an optional caption, and an export width. The form validates on submit, shows the errors under each field, moves focus to the first invalid field, and saves.
import { Button, NumberField, Stack, Text, TextArea, TextField } from "@codeui/solid";
import { createSignal, Show } from "solid-js";
import { createStore } from "solid-js";
type ExportSettings = {
fileName: string;
caption: string;
width: number | null | undefined;
};
type Errors = Partial<Record<keyof ExportSettings, string>>;
function validate(values: ExportSettings): Errors {
const errors: Errors = {};
if (!values.fileName.trim()) errors.fileName = "Enter a file name.";
else if (!/^[\w-]+$/.test(values.fileName)) errors.fileName = "Use letters, numbers, dashes and underscores.";
if (values.caption.length > 120) errors.caption = "Keep the caption under 120 characters.";
if (values.width == null) errors.width = "Enter an export width.";
return errors;
}
/** Stands in for a request to your API. */
function saveExportSettings(values: ExportSettings) {
return new Promise<ExportSettings>(resolve => setTimeout(() => resolve(values), 600));
}
export default function ExportForm() {
const [values, setValues] = createStore<ExportSettings>({ fileName: "", caption: "", width: 1280 });
const [submitted, setSubmitted] = createSignal(false);
const [saving, setSaving] = createSignal(false);
const [saved, setSaved] = createSignal<string>();
// Show errors only after the first submit, then update them on every edit.
const errors = () => (submitted() ? validate(values) : {});
const state = (key: keyof ExportSettings) => (errors()[key] ? "invalid" : "valid");
const onSubmit = async (event: SubmitEvent) => {
event.preventDefault();
setSubmitted(true);
setSaved(undefined);
if (Object.keys(validate(values)).length > 0) {
// Move focus to the first field that failed, so keyboard and screen reader users land on it.
const form = event.currentTarget as HTMLFormElement;
queueMicrotask(() => form.querySelector<HTMLElement>("[aria-invalid='true']")?.focus());
return;
}
setSaving(true);
const result = await saveExportSettings({ ...values });
setSaving(false);
setSaved(`Saved ${result.fileName}.png at ${result.width} px.`);
};
return (
<form novalidate onSubmit={onSubmit} style={{ width: "360px" }}>
<Stack gap="4">
<TextField
name="fileName"
label="File name"
required
autocomplete="off"
description="Without the extension."
value={values.fileName}
onChange={value => setValues(draft => { draft.fileName = value; })}
validationState={state("fileName")}
errorMessage={errors().fileName}
/>
<TextArea
name="caption"
label="Caption"
description="Optional. Shown under the image."
options={{ autoResize: true }}
value={values.caption}
onChange={value => setValues(draft => { draft.caption = value; })}
validationState={state("caption")}
errorMessage={errors().caption}
/>
<NumberField
name="width"
label="Export width"
required
postfix=" px"
min={320}
max={4096}
step={160}
value={values.width}
onChange={value => setValues(draft => { draft.width = value; })}
validationState={state("width")}
errorMessage={errors().width}
/>
<Stack direction="row" gap="3" align="center">
<Button type="submit" variant="primary" loading={saving()}>
Save settings
</Button>
<div role="status">
<Show when={saved()}>
<Text size="xs" tone="success">
{saved()}
</Text>
</Show>
</div>
</Stack>
</Stack>
</form>
);
}Submit the empty form to see the errors. Fix a field and its error clears as you type.
Keep the values in one store
type ExportSettings = {
fileName: string;
caption: string;
width: number | null | undefined;
};
const [values, setValues] = createStore<ExportSettings>({ fileName: "", caption: "", width: 1280 });Control every field with value and onChange, and write to the store. onChange on TextField and TextArea receives the string. onChange on NumberField receives a number, or null when the input is empty. Type the width as number | null | undefined to match it.
Read the values from the store, not from FormData. NumberField submits its formatted text, such as 1 280 px, and not the number.
Write one validate function
function validate(values: ExportSettings): Errors {
const errors: Errors = {};
if (!values.fileName.trim()) errors.fileName = "Enter a file name.";
else if (!/^[\w-]+$/.test(values.fileName)) errors.fileName = "Use letters, numbers, dashes and underscores.";
if (values.caption.length > 120) errors.caption = "Keep the caption under 120 characters.";
if (values.width == null) errors.width = "Enter an export width.";
return errors;
}The kit fields do not validate. They show the state you give them. A plain function from values to messages keeps the rules in one place, and you can run the same function on the server. Write each message as what to do, not what went wrong.
Show errors after the first submit
const errors = () => (submitted() ? validate(values) : {});
const state = (key: keyof ExportSettings) => (errors()[key] ? "invalid" : "valid");Pass validationState={state("fileName")} and errorMessage={errors().fileName} to each field. A field shows its errorMessage only while validationState is "invalid", and sets aria-invalid on the input. The input lists the message in aria-describedby, so a screen reader reads it with the field.
Before the first submit, errors() is empty and no field is invalid. After it, the errors follow every edit. Use description for the rule that never changes, such as "Without the extension.", and errorMessage for the problem with the current value.
Submit the form
const onSubmit = async (event: SubmitEvent) => {
event.preventDefault();
setSubmitted(true);
setSaved(undefined);
if (Object.keys(validate(values)).length > 0) {
// Move focus to the first field that failed, so keyboard and screen reader users land on it.
const form = event.currentTarget as HTMLFormElement;
queueMicrotask(() => form.querySelector<HTMLElement>("[aria-invalid='true']")?.focus());
return;
}
setSaving(true);
const result = await saveExportSettings({ ...values });
setSaving(false);
setSaved(`Saved ${result.fileName}.png at ${result.width} px.`);
};Put noValidate on the form. Without it, the browser blocks the submit on a required field and shows its own bubble instead of your message. Keep required on the field anyway, because it sets aria-required on the input.
A submit button inside the form handles Enter in a TextField and a click. Pass loading to the button while the request runs. Announce the result in an element with role="status" that is in the page before the message arrives. A status region that appears with its text is not always read.
Choose the field for each value
| Value | Field | Props in the demo |
|---|---|---|
| File name, one line | TextField | required, autocomplete="off", a description for the format |
| Caption, several lines | TextArea | options={{ autoResize: true }}, so it grows with the text |
| Export width, a number | NumberField | min, max, step, and postfix=" px" |
NumberField clamps the width to min and max when the input loses focus. Validate the empty case yourself, because null is a valid value for the field.
Give each field a name so browser autofill and password managers can identify it. For a control the kit does not ship, build it with the field helpers so it matches the other fields.
Related
- TextField, TextArea, and NumberField list every prop and state.
- Field helpers build a custom field that takes
errorMessagelike these. - Build settings is for choices that apply at once, with no submit.