0

I have a title (input field) and a checkbox. I've successfully implemented a schema to require the checkbox on its own. What I want to do is, validate if something has been typed in the title, if it's empty then the checkbox is required. I tried following Yup docs but I can't get anything to work.

I've tried this, but I don't get an error when the title isn't filled.

const validationSchema = Yup.object({
title: Yup.string()
.required('Required'),
checkbox: Yup.bool()
.when('title', ({ is: true, then: Yup.bool().required('Required') }))
});

And if possible, is there a way to validate a field using a state in my component instead?

Fresh Java
  • 107
  • 1
  • 10

1 Answers1

0

Use Yup.ref().

 title: Yup.string().required('Title is required'),
 checkbox: Yup.boolean().nullable().required(Yup.ref('title'), "checkbox is required"),
Nidhi Dadiya
  • 798
  • 12
  • 31
  • This doesn't work. Is it because my elements aren't siblings? They're in the same scope/form but not direct siblings. – Fresh Java Aug 07 '20 at 10:10