Implement ShadCn form with Validation
NISHARGA KABIR
Posted on July 3, 2024
Our Goal or Funda is very simple. Follow 4 steps implement a super duper form with validation with less code
Step 0: Define a zod schema
import { z } from 'zod';
export const createDepartmentsSchema = z.object({
name: z.string().min(2, {
message: 'Please enter your full name'
}),
remarks: z.string().min(2, {
message: 'Subject must be at least 2 characters'
}),
description: z.string().min(20, {
message: 'Message must be at least 20 characters'
}),
});
schema is nothing....... if you work with mongoose you already know it otherwise just think it just like typescript. whatever condition you write here if its not match it will show you this message on the UI.
(for more about zod schema you can google it)
Now start the process :)
Step 1. Define your form.
const form = useForm<z.infer<typeof createDepartmentsSchema>>({
resolver: zodResolver(createDepartmentsSchema),
defaultValues: {
name: '',
remarks: '',
description: ''
}
});
using zodResolver connect your schema with form...
when you update you can set your current value on default values...
Step 2. Define a submit handler.
function onSubmit(values: z.infer<typeof createDepartmentsSchema>) {
console.log(values);
}
currently we do console.log here to see our form data.. later we will implement API here.
Step 3. Init your form
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className='space-y-6'>
</form>
</Form>
First Form came from ShadCN which expect default values thats why we copy our form data. (step 1)
form onSumit is the default behavior of a form. we are already familer with it.. our 90% job done here ✅
Step 4: Final Step (Now its time to import input)
If you need a input field you can use your reUsable formInput (or you can use shadcn input here)...
<FormInput
form={form}
name='name'
placeholder='Your Name'
className='!pl-8 rounded-full'
/>
FormInput just expert (form) you can think it just a connection creator between input and forms 😁
If you need Textarea
<FormTextarea form={form} name='description' />
remember only form and name is required in every field. other fields are optional...
Finally a button need for submitting this form.
<Button type='submit'>Submit<Button>
If everything works... then without data submitting form show warring....
If everything ok then.....
After submit data show data on console.
Thanks for reading ❤❤❤
Posted on July 3, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.