How to validate Yup conditionally according to react state value?

Viewed 35

I have a state called profession and I want to validate the form conditionally using Yup. I'm aware that we can validate according to another field. but in this case I'm checking the value of a react state. profession state will store the type of profession and in Yup schema I'll check the value of the profession and if it's Student I wanna have some validations.

const [profession, setProfession] = useState(""); 

const SignupSchema2 = Yup.object().shape({
     universityname: Yup.string().when("profession", {
      is: "Student",
      then: Yup.string().required("Required"),
    })
  });

  

1 Answers

A solution would be to create an object that contain both the form state and your profession string and validate based on this object

const [profession, setProfession] = useState("");
const [formValue, setFormValue] = useState({});

const SignupSchema2 = Yup.object().shape({
   profession: Yup.string(),
   form: {
     universityname: Yup.string().when("profession", {
      is: "Student",
      then: Yup.string().required("Required"),
    })
   }
  });

// when you want to validate
SignupSchema2.validate({ profession, form: formValue });
Related