skip to Main Content

I am using shadcn, zod, react-hook-form to render a form, some fields are optional and some are mandatory so they do not have the .optional() attribute.

I want to render a red * if the field is mandatory, how can i do that?

My current approach which does not work

return (
                    <FormItem>
                      <FormLabel className="text-sm font-medium text-gray-700">
                        {label}
                        {!field.isOptional && (
                          <span className="text-red-500">*</span>
                        )}
                      </FormLabel>
                      <FormControl>
                        <Input
                          {...field}
                          className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  );

2

Answers


  1. As far as I know the optional/not optional information from zod is not transferred back to rhf.

    I am sure you could parse the zod schema manually and extract the information somehow. But usually you just want to reimplement your required logic directly inside the jsx again.

    Easiest way would be to just put your asterisk element to the fields that are required and leave it out of the fields that are not required. Don’t try to overcomplicate things 🙂

    Login or Signup to reply.
  2. I feel we can’t achieve using react-hook-form but using zod.

    Please try this.

    {!(yourSchema.shape.theField instanceof z.ZodOptional) && (
      <span className="text-red-500">*</span>
    )}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search