Sign-up form
Field checks, a cross-field check, a debounced server check and server errors, built with both libraries.
Here is a sign-up form built twice: once with @lunarhue/forms and once with TanStack Form. Both versions render identical markup and talk to the same mock API, so the only difference is the form wiring. Toggle between the two builds in the preview below; they behave the same.
Bundle size
| Build | @lunarhue/forms is | @lunarhue/forms 0.2.0 | TanStack Form 1.33.5 |
|---|---|---|---|
| Forms + app | 5.2 kB smaller (27%) | 13.8 kB | 19.0 kB |
| Total | 4.9 kB smaller (6%) | 81.3 kB | 86.2 kB |
| App only | 382 B smaller (19%) | 1.6 kB | 2.0 kB |
import { createForms, debounced, fieldValidators, formValidator, pipe, useForm } from "@lunarhue/forms-react";
import { isUsernameTaken, signUp } from "../../shared/server.ts";
import { Page } from "../../shared/ui.tsx";
import { Checkbox, TextField } from "./fields.tsx";
const forms = createForms({ fields: { TextField, Checkbox } });
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
// Validators first run on blur and then on every input, which is the
// default, so nothing here sets it.
const signUpForm = forms.define({
defaultValues: { email: "", username: "", password: "", confirm: "", terms: false },
validate: {
fields: fieldValidators({
email: (email) => (emailPattern.test(email) ? undefined : { message: "Enter a valid email." }),
// The sync rules answer at once. Only a well-formed name waits for a
// pause and goes to the server. A newer run aborts the older request.
username: pipe(
(name) => (name.length < 3 ? { message: "Use at least 3 characters." } : undefined),
(name) => (/^[a-z0-9_]+$/i.test(name) ? undefined : { message: "Use letters, digits and underscores." }),
debounced(async (name, { signal }) => ((await isUsernameTaken(name, signal)) ? { message: "That username is taken." } : undefined), 400),
),
password: (password) => (password.length >= 8 ? undefined : { message: "Use at least 8 characters." }),
terms: (accepted) => (accepted ? undefined : { message: "Accept the terms to continue." }),
}),
// Sees the whole value, so it runs again when either password changes.
form: formValidator(({ password, confirm }) => {
if (confirm === "") return { fields: { confirm: { message: "Confirm your password." } } };
if (confirm !== password) return { fields: { confirm: { message: "The passwords don't match." } } };
return undefined;
}),
},
onSubmit: async (value, { store }) => {
const response = await signUp(value);
if (!response.ok) {
// Each message lands on its field and clears when the user edits it.
store.setErrors({ fields: Object.fromEntries(Object.entries(response.errors).map(([name, message]) => [name, { message }])) });
return undefined;
}
return `Welcome, ${value.username}.`;
},
});
export function App() {
const form = useForm(signUpForm);
return (
<Page title="Create an account" lede="Core only: field validators, a cross-field check, an async check and server errors.">
<form {...form.formProps}>
<form.TextField name="email" label="Email" type="email" />
<form.TextField name="username" label="Username" />
<form.TextField name="password" label="Password" type="password" />
<form.TextField name="confirm" label="Confirm password" type="password" />
<form.Checkbox name="terms" label="I accept the terms" />
<form.State select={(state) => state.submitting}>
{(submitting) => (
<div className="actions">
<button type="submit" disabled={submitting}>
{submitting ? "Creating account..." : "Create account"}
</button>
</div>
)}
</form.State>
<form.State select={(state) => state.submission}>
{(submission) => <p role="status">{submission.status === "succeeded" ? submission.result : null}</p>}
</form.State>
</form>
</Page>
);
}import { useState } from "react";
import { isUsernameTaken, signUp } from "../../shared/server.ts";
import { Page } from "../../shared/ui.tsx";
import { useAppForm } from "./form.tsx";
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
// Each check runs on every change and on blur (see useBlur in form.tsx).
// The field components show errors only once the field is blurred.
function checkEmail({ value }: { value: string }) {
return emailPattern.test(value) ? undefined : "Enter a valid email.";
}
function checkUsername({ value }: { value: string }) {
if (value.length < 3) return "Use at least 3 characters.";
if (!/^[a-z0-9_]+$/i.test(value)) return "Use letters, digits and underscores.";
return undefined;
}
async function checkUsernameFree({ value, signal }: { value: string; signal: AbortSignal }) {
return (await isUsernameTaken(value, signal)) ? "That username is taken." : undefined;
}
function checkPassword({ value }: { value: string }) {
return value.length >= 8 ? undefined : "Use at least 8 characters.";
}
function checkTerms({ value }: { value: boolean }) {
return value ? undefined : "Accept the terms to continue.";
}
export function App() {
const [welcome, setWelcome] = useState("");
const form = useAppForm({
defaultValues: { email: "", username: "", password: "", confirm: "", terms: false },
validators: {
// The request runs as a submit validator, so a refusal puts its
// messages on the fields and onSubmit doesn't run.
onSubmitAsync: async ({ value }) => {
const response = await signUp(value);
return response.ok ? undefined : { fields: response.errors };
},
},
onSubmit: ({ value }) => setWelcome(`Welcome, ${value.username}.`),
});
return (
<Page title="Create an account" lede="Core only: field validators, a cross-field check, an async check and server errors.">
<form
noValidate
onSubmit={(event) => {
event.preventDefault();
void form.handleSubmit();
}}
>
<form.AppField name="email" validators={{ onChange: checkEmail }}>
{(field) => <field.TextField label="Email" type="email" />}
</form.AppField>
<form.AppField
name="username"
validators={{
onChange: checkUsername,
// Runs only when the sync check passes. Waits for a pause in
// typing, and asks the server only after the first blur, since
// nothing shows before it.
onChangeAsyncDebounceMs: 400,
onChangeAsync: async (props) => (props.fieldApi.state.meta.isBlurred ? checkUsernameFree(props) : undefined),
}}
>
{(field) => <field.TextField label="Username" />}
</form.AppField>
<form.AppField name="password" validators={{ onChange: checkPassword }}>
{(field) => <field.TextField label="Password" type="password" />}
</form.AppField>
<form.AppField
name="confirm"
validators={{
// Runs again when the password changes.
onChangeListenTo: ["password"],
onChange: ({ value, fieldApi }) => checkConfirm(value, fieldApi.form.getFieldValue("password")),
}}
>
{(field) => <field.TextField label="Confirm password" type="password" />}
</form.AppField>
<form.AppField name="terms" validators={{ onChange: checkTerms }}>
{(field) => <field.Checkbox label="I accept the terms" />}
</form.AppField>
<form.AppForm>
<form.SubmitButton label="Create account" busyLabel="Creating account..." />
</form.AppForm>
<p role="status">{welcome}</p>
</form>
</Page>
);
}
function checkConfirm(confirm: string, password: string) {
if (confirm === "") return "Confirm your password.";
if (confirm !== password) return "The passwords don't match.";
return undefined;
}What the form does
It collects an email, username, password, confirmation, and terms checkbox. Fields show errors after their first blur and re-validate on every keystroke after that. Password confirmation validates against password, re-checking automatically whenever password changes.
Username validation runs cheap local rules (length and allowed characters) as you type, and only hits the server once the format is valid, after a 400 ms pause, aborting stale requests if you keep typing. Try ada or admin to see the server check, or [email protected] to see a server-side refusal on submit that clears as soon as you edit the email.
Where the two implementations differ
On the @lunarhue/forms side, everything uses just the core package with no plugins needed. Field rules live in validate.fields, the password match lives in validate.form, and server refusals go onto fields via setErrors. The username check is a single pipe combining two sync checks with a debounced async check: when a sync check fails, the pipe stops and never starts the timer or request. Blur-then-input validation is the default, so no timing configuration is needed.
On the TanStack Form side, the form uses createFormHook for field components, per-field validators, onChangeListenTo to re-check password confirmation, and a form-level onSubmitAsync for the server call. Matching the same behavior required a few workarounds:
- TanStack keeps
onBlurerrors stuck until the next blur even after the user fixes the value, so all rules move toonChangeand field components manually callfield.validate("change")on blur. isTouchedflips totrueon the first keystroke, so components wait forisBlurredbefore displaying errors.onChangeAsyncruns on every change, so the username validator bails out early until the field has been blurred.- The server request runs inside
onSubmitAsync(the documented way to attach server errors to fields), and because submit doesn’t store a return value, the welcome message lives in separate React state.
You will notice one small difference in the preview: TanStack’s submit ignores clicks while an async check or debounce is pending, so its button disables via canSubmit. Ours stays enabled and waits for any pending check to settle before submitting.
How bundle sizes were measured
scripts/size-compare.ts builds each app for production with Vite (minified, JavaScript only, since both share the same CSS) in three variants per library:
- Forms + app: the form library plus the app’s own form code (excluding React,
react-dom, and Zod). - Total: everything the page loads, including React and Zod.
- App only: just the form-specific app code, excluding the form libraries too.
Our packages are measured from their built dist outputs, compared against TanStack Form 1.33.5. CI re-runs this script on every PR and fails if the committed numbers drift. Both apps and their shared Playwright test suite live in examples/compare.
Last updated