简体   繁体   中英

how to validate if an array is empty using validator

I need to check if the users have filled in array values or they are empty . I went through the validator docs

but I don't see any function which works on array .

isEmpty(str) check if the string has a length of zero.

validator validates and sanitizes strings only. so none of the methods in there will help you achieve what you want. just use Array.length property.

If by empty array, you mean: []

This will do:

if(!array.length)
  console.log(`I'm not empty`);

If you mean an array with empty values, such as: [null, '']

You can use: .some to check if at least one item is empty, or .every to check that every item is empty.

const array = [null, ''];

!array.some(Boolean); // True if at least one is falsy
!array.every(Boolean); // True if every item is falsy

If you want some custom validation, you can pass your custom function too.

function empty(item) {
   // What ever you consider by empty, check it here
   // return true if it is empty
   if(typeof item === 'string')
      return !item.trim();

   return !item;
}

array.some(empty); // true if at least one is empty
array.every(empty); // true if all of them are empty

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM