Skip to content

Commit 99da8dd

Browse files
committed
fix: fix React form validation
1 parent cb9d10e commit 99da8dd

1 file changed

Lines changed: 13 additions & 2 deletions

File tree

src/components/ReactForm/ReactForm.tsx

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
'use client'
22

3-
import { useActionState, useOptimistic, useState, type FC } from 'react'
3+
import { FormEvent, useActionState, useOptimistic, useState, type FC } from 'react'
44

55
import { formSchema } from '@/constants/validation-schema'
66
import { formFields } from '@/constants/form-fields'
@@ -47,11 +47,22 @@ export const ReactForm: FC = () => {
4747

4848
const [state, formAction, isPending] = useActionState(handleFormSubmit, '')
4949

50+
const validateForm = (event: FormEvent<HTMLFormElement>) => {
51+
const formData = new FormData(event.target as HTMLFormElement)
52+
const formDataEntries = Object.fromEntries(formData.entries())
53+
const result = formSchema.safeParse(formDataEntries)
54+
55+
if (result.error) {
56+
event.preventDefault()
57+
setErrors(result.error.flatten().fieldErrors)
58+
}
59+
}
60+
5061
return (
5162
<div className="min-w-96">
5263
<h1 className="text-2xl font-bold text-center mb-4">React Form</h1>
5364

54-
<Form action={formAction}>
65+
<Form action={formAction} onSubmit={validateForm}>
5566
{formFields.map((field) => (
5667
<FieldWrapper key={field.name} errorMessage={errors?.[field.name]?.[0]}>
5768
<Label htmlFor={field.name}>{field.label}</Label>

0 commit comments

Comments
 (0)