Skip to content

Instantly share code, notes, and snippets.

@nikolovlazar
Created August 14, 2024 11:34
Show Gist options
  • Save nikolovlazar/824dd3efb67228f673e40494ed8e63a4 to your computer and use it in GitHub Desktop.
Save nikolovlazar/824dd3efb67228f673e40494ed8e63a4 to your computer and use it in GitHub Desktop.
React Hook Form + Zod validation. The form components are from the shadcn/ui library.
import { z } from 'zod'
export const signUpFormSchema = z.object({
email: z.string().email('Invalid email'),
password: z
.string()
.min(6, { message: 'Password must be at least 6 characters' }),
confirmPassword: z
.string()
.min(6, { message: 'Password must be at least 6 characters' }),
})
import { z } from 'zod'
import { zodResolver } from '@hookform/resolvers/zod'
import { useForm } from 'react-hook-form'
import { signUpFormSchema } from '@/interface-adapters/validation-schemas/auth'
export const SignUpForm = () => {
const form = useForm<z.infer<typeof signUpFormSchema>>({
resolver: zodResolver(signUpFormSchema),
defaultValues: {
email: '',
password: '',
confirmPassword: '',
},
})
async function onSubmit(values: z.infer<typeof signUpFormSchema>) {
const data = new FormData()
data.append('email', values.email)
data.append('password', values.password)
data.append('confirmPassword', values.confirmPassword)
const [output] = await signUp(data)
if (output) {
if (output.errors) {
output.errors.email &&
form.setError('email', { message: output.errors.email })
output.errors.password &&
form.setError('password', { message: output.errors.password })
output.errors.confirmPassword &&
form.setError('confirmPassword', {
message: output.errors.confirmPassword,
})
} else if (output.success) {
toast.success('Sign up successful!', {
description: 'Check your email for further instructions',
})
}
}
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<div className="grid gap-4">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input
type="email"
placeholder="[email protected]"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Password</FormLabel>
<FormControl>
<Input
type="password"
placeholder="password12345"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="confirmPassword"
render={({ field }) => (
<FormItem>
<FormLabel>Confirm Password</FormLabel>
<FormControl>
<Input
type="password"
placeholder="password12345"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" className="w-full">
Sign up
</Button>
</div>
</form>
</Form>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment