DEV Community

Cover image for Implement ShadCn form with Validation
NISHARGA KABIR
NISHARGA KABIR

Posted on

Implement ShadCn form with Validation

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'
    }), 
});


Enter fullscreen mode Exit fullscreen mode

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: ''
      }
});


Enter fullscreen mode Exit fullscreen mode

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);
 }


Enter fullscreen mode Exit fullscreen mode

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>


Enter fullscreen mode Exit fullscreen mode

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'
/>


Enter fullscreen mode Exit fullscreen mode

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' />


Enter fullscreen mode Exit fullscreen mode

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>


Enter fullscreen mode Exit fullscreen mode

If everything works... then without data submitting form show warring....

without validation

If everything ok then.....
After submit data show data on console.

after submit console

Thanks for reading ❤❤❤

Top comments (0)