aarti
aarti

Reputation: 175

Show validation when user selects specific radio button

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?

Upvotes: 0

Views: 1834

Answers (1)

senthil balaji
senthil balaji

Reputation: 628

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(),
});

Upvotes: 1

Related Questions