Validating Arrays in JavaScript

548
SHARES
2.5k
VIEWS

In this JavaScript arrays tutorial, we will learn how we can validate content in javascript arrays that meet a certain criteria specified by us. We will use the javascript every() array function to accomplish that. This method will check every element passes a given criterion. For example, the code below checks to ensure that every element in the array contains alphabetical characters:

function testArrayValue (element,index,array) {
  let textExp = /^[a-zA-Z]+$/;
  return textExp.test(element);
}

var elemSet = ["**",555,"aaa","abc","-",34,"AAA"];


// running test
let result = elemSet.every(testArrayValue);

console.log(result); // false

let fruitNames = ["banana","mango","orange"];

result = fruitNames.every(testArrayValue);

console.log(result); // true

Remeber,every()  method do not work against all array elements: they only process as many array elements as necessary to fulfill their functionality.

Leave a Reply

Your email address will not be published. Required fields are marked *