Validating a nested and conditionally optional Yup scheme

Asked

Viewed 298 times

2

I am facing a problem when trying to validate a scheme nested with Yup ().

My scenario is that I have the following payload (which may not always contain maxAge and maxAge, but at least one of them):

{
  name: 'userName',
  calc: [{
    maxAge:{
      day:'0',
      month:'0',
      year:'5',
    },
    minAge:{
      day:'12',
      month:'12',
      year:'4',
    }
  }],
}

The problem is that maxAge and Minage are "optional", but at least one is required, so that internal content (day, month, year) is optional, but if a maxAge or Minage is passed, at least one of the internal content is required.

I tried the following code:

const Yup = require('yup');

(async () => {
  try {
    const schema = Yup.object().shape({
      name: Yup.string()
        .required()
        .trim()
        .min(2, `Name must have at least 3 characters`)
        .max(50, `Name must have at maximum 50 characters`)
        .matches(/^[A-Za-zÀ-ÿ\- &]*$/, 'Name is not valid')
        .required(),
      calc: Yup.array().of(
        Yup.object()
        .shape(
          { 
            maxAge: Yup.object()
            .shape({
              year: Yup.string().optional(),
              month: Yup.string().optional(),
              days: Yup.string().optional()
            }).when('minAge', {
              is: '' || undefined || {} || null,
              then: Yup.object().shape({
                year: Yup.string(),
                month: Yup.string(),
                days: Yup.string()
              }).required('This minAge is required.'),
              otherwise: Yup.object()
            }), 

            minAge: Yup.object()
            .shape({
              year: Yup.string().optional(),
              month: Yup.string().optional(),
              days: Yup.string().optional()
            }).when('maxAge', {
              is: '' || undefined || {} || null,
              then: Yup.object().shape({
                year: Yup.string(),
                month: Yup.string(),
                days: Yup.string()
              }).required('This minAge is required.'),
              otherwise: Yup.object()
            }),

          },
          [['minAge', 'maxAge']]
        )
        .required(),
      )
    });

    let test = await schema.validate(
      {
        name: 'Jonas',
        calc: [{

        }],
      },
      { abortEarly: false }
    );
    console.log(JSON.stringify(test));
  } catch (err) {
    console.log(err);
  }
})();
  • You can do your own validation. In case you would put the validation function on calc and do whatever you want in the job, like in example. Have you ever tried anything like?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.