javascriptreactjsformikyup

In react, formik and yup how to skip validation if dynamic array value if undefined or empty make it optional


This is my aaray :

translator_services: (4) [empty × 3, {translator_category_description: "sa",translator_category_id: "6672a5a8b07e9bc1b7e36a5c",translator_category_type_id: ['6672a5a8b07e9bc1b7e36a5a']}]

This the error from Yup :

translator_services: Array(3)<br>
0: {translator_category_id: 'Required', translator_category_description: 'Description is required.'}<br>
1: {translator_category_id: 'Required', translator_category_description: 'Description is required.'}<br>
2: {translator_category_id: 'Required', translator_category_description: 'Description is required.'}<br>

This is validation code :

translator_services: Yup.array().of(
    Yup.object().shape({
      translator_category_id:
        Yup.string().required("Required"),
      translator_category_description:
        Yup.string().nullable().required("Description is required."),
      
      translator_category_type_id: Yup.array().nullable().min(
        1,
        "Select at least one service type"
      ),
    })
  ),

Should only validate if the array value is defined or not empty else skip the validation. Thanks in advance


Solution

  • What you need to use for this cases is the .when() function. Here's the docs about it: https://github.com/jquense/yup?tab=readme-ov-file#schemawhenkeys-string--string-builder-object--values-any-schema--schema-schema

    So, your code could be something like:

     translator_services: Yup.array().of(
      Yup.object().shape({
        translator_category_id: Yup.string()
         .when('translator_category_type_id', {
           is: (val) => val.length, 
           then: Yup.string().required("Required"), // If translator_category_type_id has values, then translator_category_id is required
            otherwise: Yup.string(),
            }),
            translator_category_description: Yup.string().nullable()
            .when('translator_category_type_id', {
              is: (val) => val.length, 
              then: Yup.string().required("Description is required."),// If translator_category_type_id has values, then translator_category_description is required
              otherwise: Yup.string(),
            }),
            translator_category_type_id: Yup.array().nullable().min(
              1,
              "Select at least one service type"
            ),
          })
        )
    

    Hope it helps!