Timur Catakli
Timur Catakli

Reputation: 1456

Validation schema help needed

const ValidationSchema = Yup.object().shape({
  name: Yup.string()
    .min(2, 'String too short!')
    .max(50, 'String too long!')
    .required('Field is required!')
    .lowercase(),
  phases: Yup.array().of(
    Yup.object().shape({
      sla_type: Yup.string(),
      sla: Yup.number(),
    }),
  ),
});

First of all I just started to learn YUP and love it. kudos to the team...

Above is my validation schema. Under Phases I have two fields: sla_type and sla

Here is what I am trying to accomplish:

  1. If sla_type is empty, and sla is also empty no validation required, no values required
  2. If sla_type === 'minutes', sla should be min(1), max(60)
  3. If sla_type === 'hours', sla should be min(1), max(24)
  4. If sla_type === 'days', sla should be min(1), max(90)

How can I achieve this please?

Upvotes: 2

Views: 85

Answers (1)

jayarjo
jayarjo

Reputation: 16726

You can make use of yup.when(), like this:

const ValidationSchema = Yup.object().shape({
    name: Yup.string()
      .min(2, 'String too short!')
      .max(50, 'String too long!')
      .required('Field is required!')
      .lowercase(),
    phases: Yup.array().of(

      Yup.object().shape({
        sla_type: Yup.string().oneOf(['minutes', 'hours', 'days']),
        sla: Yup.number().when('sla_type', (sla_type) => {
          switch (sla_type) {
            case 'minutes': 
              return Yup.number().min(1).max(60)
            case 'hours': 
              return Yup.number().min(1).max(24)
            case 'days': 
              return Yup.number().min(1).max(90)
          }
        })
      })

    )
  });

Upvotes: 1

Related Questions