Yup validation, strings in array lowercase and not required

208 Views Asked by At

I need a validation of array of strings(tags). Strings should be in lower case, max 14 and not required.

I tried this, but I need it to make not required, i.e. they should be allowed to be null, undefined or an empty array

tags: yup.array()
.max(14, "Max 14 tags allowed!")
.test("is tag", "All words to lower case!", (arr) => {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] !== arr[i].toLowerCase()) {
            return false;
        }
    }
    return true; 
}),
1

There are 1 best solutions below

0
jrcamatog On

You can add nullable to allow null and undefined. I also included a much shorter checking if the tags are all lowercase.

tags: yup.array()
  .nullable()
  .max(14, "Max 14 tags allowed!")
  .test("is tag", "All words to lower case!", (arr) => {
    return !arr.find((tag) => tag !== tag.toLowerCase()); 
  }),