"use client";
import { FormError } from "@/components/ui/form-error";
import { useForm } from "@tanstack/react-form";
export default function FormErrorDemo() {
const form = useForm({
defaultValues: {
email: "",
},
validators: {
onSubmit: ({ value }: { value: { email: string } }) => {
if (!value.email) {
return { fields: { email: "Email is required" } };
}
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value.email)) {
return { fields: { email: "Please enter a valid email address" } };
}
return undefined;
},
},
onSubmit: async ({ value }: { value: { email: string } }) => {
console.log(value);
},
});
return (
<form
className="flex w-full max-w-sm flex-col gap-2"
onSubmit={(e) => {
e.preventDefault();
e.stopPropagation();
form.handleSubmit();
}}
>
<label htmlFor="email" className="text-sm font-medium">
Email
</label>
<form.Field name="email">
{(field) => (
<input
id="email"
name={field.name}
value={field.state.value}
onChange={(e) => field.handleChange(e.target.value)}
placeholder="you@example.com"
className="h-9 rounded-md border border-input bg-transparent px-3 text-sm shadow-sm outline-none transition-colors focus-visible:ring-1 focus-visible:ring-ring"
/>
)}
</form.Field>
<FormError form={form} name="email" />
<button
type="submit"
className="mt-1 h-9 rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90"
>
Submit
</button>
</form>
);
}