1

I have an an array that returns the values such as the following:

//Eg 1    [ [ "214323", "34243" ], [ "3333", "123" ] ]

//Eg 2    [ [ "214323" ],[ "3333" ] ]

I want to validate if the array holds only numbers with no spaces or null, else I would like to throw an error. This is my following code and it does not work in the above example. It throws out an error even though all values are numeric.

for (var i = 0; i <= arrayVals.length; i++) {
    if(!(/^\d+$/.test(arrayVals[i]))) {
        err_comp=true;

        }   
}

if( err_comp ==true) {
        alert( 'The value has to be only numeric.');
} 

3 Answers 3

2

You have an array of arrays, thus you need two loops:

var err_comp = false;
for (var i = 0; i < arrayVals.length; i++) {
  var arr = arrayVals[i];
  for (var j = 0; j < arr.length; j++) {
    if (!(/^\d+$/.test(arr[j]))) {
        err_comp = true;
    }   
  }
}

Otherwise, you'd be testing /^\d+$/.test([ "214323", "34243" ]).

Sign up to request clarification or add additional context in comments.

Comments

2

you should not use <= because you start with 0 you should use <:

for (var i = 0; i < arrayVals.length;

1 Comment

But isNaN won't throw any error with something like ' 10 ', but he doesn't want spaces.
1
multi_arr.every(function(arr) {
    return arr.every(function(n) {
        return /^\d+$/.test(n);
    });
});

You can change the test as you need, and you can add a .every patch for IE8 if you want.

And you can make reusable your functions.

function forEveryArray(fn) {
    return function every_array(arr) {
        return arr.every(fn)
    }
}

function isNumber(n) { return /^\d+$/.test(n); }


multi_arr.every(forEveryArray(isNumber));

2 Comments

While it's a good solution, this won't work for versions of IE < 9.
@João: That should be considered a feature, no? ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.