1

I have a form component that uses React-Hook-Forms and Zod for validation. The validation is working just fine for all input components except radio buttons.For instance, if I have two options, and the user checks one option, zod throws an error for the option that isn't checked.

The radio buttons are nested in one parent div and there's one error message container for both options. Zod, however, doesn't seem to be aware that if one option has been checked, it shouldn't throw an error.

form component:

<form onSubmit={handleSubmit(onSubmit)}>
 {/* other fields ... */}
        <div>
          <p>Receive PIN through</p>
          <label htmlFor="receive-pin-sms">
            <input
              type="radio"
              value="SMS"
              id="receive-pin-sms"
              {...register("smsOrCall")}
              name="radio"
            />
            SMS
          </label>
          <label htmlFor="receive-pin-call">
            <input
              type="radio"
              value="Call"
              id="receive-pin-call"
              {...register("smsOrCall")}
              name="radio"
            />
            Call
          </label>
          {errors.state?.message && (
            <p>{errors.state.message}</p>
          )}
        </div>
        <div>
          <button
            type="submit"
          >
            Next Step
          </button>
        </div>
      </form>

validation schema:

const FormSchema = z.object({
  // ...
  smsOrCall: z
    .string()
    .min(1, { message: "Please select a value" })
    .max(260, { message: "The name is too long" }),
});

RHF useForm:

const BusinessInformationForm: React.FC<BusinessInformationFormProps> = () => {
  const {
    register,
    formState: { errors },
    watch,
    handleSubmit,
    setValue,
  } = useForm<BusinessInformationFormInput>({
    resolver: zodResolver(FormSchema),
    defaultValues: {
      // ...
      smsOrCall: "SMS",
    },
  });

I'm persisting the form values to localStorage like so:


  if (typeof window !== "undefined") {
    useFormPersist("businessInformationData", {
      watch,
      setValue,
      storage: window.localStorage,
    });
  }

1 Answer 1

0

Change:

{errors.state?.message && (
<p>{errors.state.message}</p>
)}

to

{errors.smsOrCall?.message && (
<p className="pl-5 text-red-700 mt-1">{errors.smsOrCall.message}</p>
)}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.