← Back to patterns

Form pattern

Using form() with progressive enhancement

Pattern Usage:

// In remote file:
export const testForm = form(
  z.object({
    message: z.string().min(1),
    count: z.number().default(0) // .as('number') sends a real number
  }),
  async (data) => {
    // Process form data
    return { success: true, data };
  }
);

// In component:
<form {...testForm.enhance(async ({ submit }) => {
  isSubmitting = true;
  try {
    if (!(await submit())) return; // false = validation failed
    const result = testForm.result; // Result available here

    // Programmatic field control using .fields API
    const count = testForm.fields.count.value() ?? 0;
    testForm.fields.count.set(count + 1);

    toast.success('Form submitted!');
  } finally {
    isSubmitting = false;
  }
})}>
  <input {...testForm.fields.message.as('text')} />
  <input {...testForm.fields.count.as('number')} />
  <button type="submit">Submit</button>
</form>

Live Demo:

How it works: Forms use progressive enhancement - they work without JavaScript but enhance with client-side validation and loading states when JS is available. The .enhance() method intercepts submission, handles validation, and provides hooks for loading states. The .fields API allows programmatic control - use .fields.count.value() to read and .fields.count.set() to update field values. Try submitting multiple times to see the count auto-increment!