Show validation when user selects specific radio button

1.7k views Asked by At

I have two radio buttons (yes/no) in React.js with Formik and Yup packages used in my projects.

I want to provide a validation message using schema when the user selects the NO option out of the two.

I am able to provide the required validator with Yup though.

Can anyone help me with this?

1

There are 1 answers

0
senthil balaji On BEST ANSWER

I tried following one and it worked,

yup
  .string()
  .test("is-no", "value cannot be No", value => value !== "no")
  .validate("A")
  .then(data => console.log(data))
  .catch(data => console.log(data.message));

Also, this is straight validation, was not used in any form.

To use this in form, you could reuse the schema but not use validate as part of the schema.

for example, your schema can be,

yup.object().shape({
  name: yup.string(),
  yesOrNoField: yup
    .string()
    .test("only-yes", "Please select YES only", value => value !== "no"),
  anyNumberField: yup.number().required(),
});