Как проверить вложенную и условно необязательную схему Yup - PullRequest
0 голосов
/ 27 мая 2020

У меня проблема, когда я пытаюсь проверить вложенную схему с помощью Yup ().

Мой ценник, у меня есть следующая полезная нагрузка (которая не всегда может содержать maxAge и maxAge, но хотя бы один из них):


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

Проблема в том, что maxAge и minAge являются «необязательными», но требуется хотя бы один, так как содержимое внутри (день, месяц, год) необязательно , но если передан один maxAge или minAge, то требуется хотя бы одно внутреннее содержимое.

Я пробовал следующий код:

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


...