Home > database >  yup validation not showing error if field is empty
yup validation not showing error if field is empty

Time:06-13

I've two tabs, auto and manual.

When i switch the tab to manual, it should only validate the tracking_number. If switch to "auto", it should validate the recipient_name.

const validationschema= yup.object().shape({
    tab: yup.string().oneOf([
      "auto",
      "manual",
    ])
      .required(),
    tracking_number: yup.string().when("tab", {
      is: "manual",
      then: yup.string().required()
    }),
   recipient_name: yup.string().when("tab", {
     is: "auto",
     then: yup.string().required()
   })
})

But this code doesn't work, it wont show any error. I did initialize the initialValue.

<Formik
          initialValues={{
            tab: "auto",
            tracking_number: "",
            recipient_name: contact_name || "",
          }}
          validationSchema={validationschema}
          onSubmit={handleOnChange}
        >

Any ideas?

CodePudding user response:

End up using if else.

const validationSchema = (tab) => {
    let shape;
    if (tab === "auto") {
      shape = {
        recipient_name: yup.string().required(),
      }
    } else if (tab === "manual") {
      shape = {
        tracking_number: yup.string().required(),
      }
    }
    const schema = yup.object().shape(shape);
    return schema;
  }
  • Related