-
-
Save catalinpit/233e9339ccf85f5e259fbd94cd757565 to your computer and use it in GitHub Desktop.
React Hook Form with Zod and TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useForm } from 'react-hook-form'; | |
import { zodResolver } from '@hookform/resolvers/zod'; | |
import * as z from 'zod'; | |
const FormSchema = z.object({ | |
username: z.string(), | |
email: z.string(), | |
isAdmin: z.boolean(), | |
createdAt: z.coerce.date(), | |
}); | |
type FormInput = z.infer<typeof FormSchema>; | |
export default function Form() { | |
const { | |
register, | |
handleSubmit, | |
formState: { errors }, | |
} = useForm<FormInput>({ | |
resolver: zodResolver(FormSchema), | |
defaultValues: { | |
username: '', | |
email: '', | |
isAdmin: true, | |
createdAt: new Date(), | |
}, | |
}); | |
return ( | |
<form | |
className="flex flex-col mt-10 bg-white px-4 py-5 shadow rounded-lg sm:m-6 sm:p-6 w-full lg:w-3/6 text-gray-600" | |
onSubmit={handleSubmit((d) => console.log(d))} | |
> | |
<div className="flex flex-col mt-4"> | |
<label htmlFor="username">Username</label> | |
<input | |
className="mt-2 border-solid border-gray-300 border py-2 px-4 w-full rounded focus:outline-none focus:ring focus:ring-purple-500" | |
id="username" | |
{...register('username')} | |
/> | |
{errors?.username?.message && ( | |
<p className="text-red-700 mt-1"> | |
{errors.username.message} | |
</p> | |
)} | |
</div> | |
<div className="flex flex-col mt-4"> | |
<label htmlFor="email">Email</label> | |
<input | |
className="mt-2 border-solid border-gray-300 border py-2 px-4 w-full rounded focus:outline-none focus:ring focus:ring-purple-500" | |
id="email" | |
{...register('email')} | |
/> | |
{errors?.email?.message && ( | |
<p className="text-red-700 mt-1">{errors.email.message}</p> | |
)} | |
</div> | |
<div className="mt-4"> | |
<label htmlFor="isAdmin">IsAdmin</label> | |
<input | |
className="ml-2" | |
id="isAdmin" | |
type="checkbox" | |
{...register('isAdmin')} | |
/> | |
</div> | |
<div className="flex flex-col mt-4"> | |
<label htmlFor="createdAt">Creation Date</label> | |
<input | |
className="mt-2 border-solid border-gray-300 border py-2 px-4 w-full rounded focus:outline-none focus:ring focus:ring-purple-500" | |
id="createdAt" | |
type="date" | |
{...register('createdAt')} | |
/> | |
{errors?.createdAt?.message && ( | |
<p className="text-red-700 mt-1"> | |
{errors.createdAt.message} | |
</p> | |
)} | |
</div> | |
<button | |
className="bg-purple-600 p-3 mt-12 rounded-lg text-white font-medium m-auto w-3/6 hover:opacity-75" | |
type="submit" | |
> | |
Submit | |
</button> | |
</form> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment