How to create a Yup validation for a Map in React, given Yup.map() does not exist?

182 Views Asked by At

I have a field called "myMapField", which needs to be a map with string keys to a string value and I also need to validate the keys in the map against elements in some other field called "myArrayField".

Example: myMapField can look like

{"employee1": "code1", "employee2": "code2"} 

and myArrayField can look like

["employee1", "employee2", "employee3"]

In above, myMapField should have type string key to string value and the keys in it should be a subset of values from myArrayField based on some conditional filtering.

Below is the validation schema that works for the array field and now I want to add the validation for map field.

const validationSchema = Yup.object().shape({
   myArrayField: Yup.array()
        .of(Yup.string())
        .min(1, 'This Field is Required')
        .required('This Field is Required'),
   myMapField: Yup. // some validation here to check type of key-value and check keys of myMapField to be subset of values in myArrayField
});

How can I add this validation for myMapField, given there is no Yup.map()?

1

There are 1 best solutions below

4
Liap On

You can use Schema.test for custom validation

And then using this.parent to access the myArrayField value (arrow function is not valid here)

Finally using js to check if map is valid like you desire.

const schema = yup.object().shape({
  myArrayField: yup
    .array()
    .of(yup.string())
    .min(1, "This Field is Required")
    .required("This Field is Required"),

  myMapField: yup.object().test("validMap", "Map is invalid", function (val) {
    const arrayFieldValue = this.parent.myArrayField;

    // check function
    const isValid = Object.keys(val).every((key) => arrayFieldValue.includes(key));

    return isValid;
  }),
});

Demo