"use client"; import { Button } from "@azmr/ui/button"; import { Field } from "@azmr/ui/field"; import { ErrorSummary, Fieldset, FormSection } from "@azmr/ui/form"; import { Input, Textarea } from "@azmr/ui/input"; import { Separator } from "@azmr/ui/layout"; import { type FormEvent, useState } from "react"; type Name = "business" | "gst" | "email" | "phone" | "city" | "postcode" | "reminders"; type Errors = Partial>; // Validate on submit, in the order the fields appear, so the summary lists them top to bottom. function validate(data: FormData): Errors { const value = (name: string) => String(data.get(name) ?? "").trim(); const errors: Errors = {}; if (value("business") === "") errors.business = "Enter your business name"; if (value("gst") && !/^\d{3}-?\d{3}-?\d{3}$/.test(value("gst"))) { errors.gst = "Enter a GST number with 9 digits, like 123-456-789"; } if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value("email"))) { errors.email = "Enter an email address like accounts@example.co.nz"; } if (value("phone") && !/^\+?[\d\s-]{7,}$/.test(value("phone"))) { errors.phone = "Enter a phone number, like 09 123 4567"; } if (value("city") === "") errors.city = "Enter a town or city"; if (!/^\d{4}$/.test(value("postcode"))) errors.postcode = "Enter a 4-digit postcode"; if (data.getAll("reminders").length === 0) { errors.reminders = "Choose at least one way to send reminders"; } return errors; } const REMINDERS = [ { value: "email", label: "Email", checked: true }, { value: "sms", label: "Text message", checked: false }, { value: "post", label: "Post", checked: false }, ]; export default function FormSettings() { const [errors, setErrors] = useState({}); const [submitCount, setSubmitCount] = useState(0); const [saved, setSaved] = useState(false); function onSubmit(event: FormEvent) { event.preventDefault(); const found = validate(new FormData(event.currentTarget)); setErrors(found); setSubmitCount((count) => count + 1); setSaved(Object.keys(found).length === 0); } return (
{REMINDERS.map((option) => ( ))}