简体   繁体   中英

Conditional Formik Form Validation Using Yup

I have a form field (shapes) that should be required when at least one of two other fields (colors & sizes) next to it are filled out. I've tried using a logical OR (||) operator, but it doesn't seem to be working. At the moment, the shapes field is only dependent on the colors field; however, if I were to switch the places of the 'colors' and 'sizes' in the OR condition, the shapes field is then only dependent on the sizes field.

This is how my code currently looks:

const formSchema = Yup.object().shape({
  colors: Yup.string().when('sizes', {
    is: (value) => Boolean(value),
    then: Yup.string().required,
    otherwise: Yup.string().nullable(),
  }),
  sizes: Yup.string().when('colors', {
    is: (value) => Boolean(value),
    then: Yup.string().required,
    otherwise: Yup.string().nullable(),
  }),
  shapes: Yup.string().when('colors' || 'sizes', {
    is: (value) => Boolean(value),
    then: Yup.string().required,
    otherwise: Yup.string().nullable(),
  }),
}, ['colors', 'sizes']);

I have a hunch that the way how I structured the OR condition for shapes is the issue. I'd appreciate it if someone could help me understand why my code above isn't working the way I'm desiring.

The following code achieves what I was attempting earlier:

const formSchema = Yup.object().shape({
  colors: Yup.string().when('sizes', {
    is: (value) => Boolean(value),
    then: Yup.string().required,
    otherwise: Yup.string().nullable(),
  }),
  sizes: Yup.string().when('colors', {
    is: (value) => Boolean(value),
    then: Yup.string().required,
    otherwise: Yup.string().nullable(),
  }),
  shapes: Yup.string().when(['colors', 'sizes'], {
    is: (colors, sizes) => Boolean(colors) || Boolean(sizes),
    then: Yup.string().required,
    otherwise: Yup.string().nullable(),
  }),
}, ['colors', 'sizes']); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM