Next.js Discord

Discord Forum

zod schema validation on client side with server action

Unanswered
Almond stone wasp posted this in #help-forum
Open in Discord
Almond stone waspOP
const formSchema = z.object({
  from: z.string().min(2, {
    message: "Your email ID is required",
  }),
  to: z.string().min(2, {
    message: "Applicant email ID is required",
  }),


i am using shadcn form, how can i show the validations on client side with server action

SERVER ACTIONS
"use server"
import { z } from 'zod'

const sendEmailFormSchema = z.object({
      subject: z.string().min(3, {
        message: "Subject is required and must be of atleast 3 characters.",
      }),
      message: z.string().min(10, {
        message: "Subject is required and must be of atleast 10 characters.",
      }),
})


export async function SendEmail(formData : 
    //////

    const parsedBody = sendEmailFormSchema.safeParse({
        subject: formData.get('subject'),
        message: formData.get('message'),
    })

    if (!parsedBody?.success) {
        return BAD_REQUEST_ACTION("Either message or subject is not valid");
    }
    ////
    try {
      ////////
    } catch (error) {
      /////////
    }
}


is it possible or i need to do it differently ?

2 Replies

Almond stone waspOP
thanks i will check 🙏