0

(Just want to note that I have checked other similar questions to mine but couldn't locate any that didn't use regex and the ones that didn't, didn't seem to work for my situation.)

Given a textarea field where a user can enter multiple IP addresses as a string separated by a comma, using JavaScript, what would be the best means to validate all these comma separated IP addresses, for example:

1.1.1.1,2.2.2.2,3.3.3.,4.4.4.256

I obviously need to test for valid IP ranges as well as the three dots and four numbers.

I would prefer a solution that doesn't use regex.

halfer
  • 19,824
  • 17
  • 99
  • 186
tonyf
  • 34,479
  • 49
  • 157
  • 246
  • 2
    What's wrong with regex, and also have you tried something so far? Like, splitting over `"."` and checking if each element is a number between 0 and 255? – Jeremy Thille Apr 09 '19 at 13:02

4 Answers4

1

You can split each ip and check if the numbers are valid. Also you can check if the dots (.) are 4.

function validateIp(ip) {
    if ( ip == null || ip === '' ) {
    return true;
  }

  const parts = ip.split('.');
  if(parts.length !== 4) {
    return true;
  }

  for(let i = 0; i < parts.length; i++) {
    const part = parseInt(parts[i]);
    if(part < 0 || part > 255) {
        return true;
    }
  }

  if(ip.endsWith('.')) {
    return true;
  }

  return false;
}

const input = '1.1.1.1,2.2.2.2,3.3.3.,4.4.4.256';
const arr = input.split(',');
const wrongIps = arr.filter(validateIp);


console.log(arr)
console.log(wrongIps)

Of course, you can do the opposite thing and get only the valid IP addresses.

Example

Vasileios Pallas
  • 4,801
  • 4
  • 33
  • 50
0

with String.prototype.split and Array.prototype.every

const isValidIP = (ip) => {
  const ranges = ip && ip.trim().split('.');
  
  if(ranges && ranges.length === 4) {
    return ranges.every(range => range && !/\s/g.test(range) && (255 - range) >= 0);
  }
  
  return false;
}

const isValidIPs = (input) => input && input.split(',').every(isValidIP);


console.log(isValidIPs('1.1.1.1,2.2.2.2,3.3.3.,4.4.4.256'));  // false
console.log(isValidIPs('1.1.1.1,2.2.2.2,4.4.4.256'));         // false
console.log(isValidIPs('1.1.1.1,2.2.2.2'));                   // true
// with space between range
console.log(isValidIPs('1.1.1. 1, 2.2.2.2'));                 // false
// with space
console.log(isValidIPs(' 1.1.1.1 , 2.2.2.2 '));               // true
ajai Jothi
  • 2,284
  • 1
  • 8
  • 16
0

try this way :

var ip = "1.1.1.1,2.2.2,3.3.3.,4.4.4.256";
ip = ip.split(',');
ip.forEach(function(v,k){
 var ips = v.split('.');
 if(ips.length == 4){
  var flagip = 0;
  ips.forEach(function(v,k){
   if(isNaN(parseInt(v)) || parseInt(v) < 0 || parseInt(v) > 255){
    flagip = 1;
    }
  });
  if(flagip == 1){
   console.log('Invalid IP Address : ' + v);
  }else{
   console.log('Valid IP Address : ' + v);
  }
 }else{
  console.log('Invalid IP Address : ' + v);
    }
});
Kamalesh M. Talaviya
  • 1,422
  • 1
  • 12
  • 26
0

Using split, map, and reduce.

  1. Split into 2D array where first dimension is the result of split(",") and the second dimension is the result of map first dimension and split(".")
  2. reduce each dimension where the first dimension is used to check the length of the second dimension. Then, check if each value in the second array is a valid positive integer (with help from this question) in the range of 0-255

This method returns false if there are spaces.

function isNormalInteger(str) {
    var n = Math.floor(Number(str));
    return n !== Infinity && String(n) === str && n >= 0;
}

function validIPs(input) {
  return input.split(",").map(ip => ip.split(".")).reduce((acc, curr) => {
    if (curr.length === 4) {
      return acc && curr.reduce((acc2, curr2) => {
        return acc2 && isNormalInteger(curr2) && parseInt(curr2) >= 0 && parseInt(curr2) < 256
      }, true)
    }
    return acc && false
  }, true)
}

let test1 = "1.1.1.1,2.2.2.2,3.3.3.,4.4.4.256"
let test2 = "1.1.1.1,2.2.2.2,3.3.3.3,4.4.4.256"
let test3 = "-1.1.1.1,2.2.2.2,3.3.3.3,4.4.4.255"
let test4 = "1.1.1.1,2.2.2.2,3.3.3.3,4.4.4.255"
let test5 = "1.1.1.1,19.91.21.63"
let test6 = "1.1.1.1,19..91.21.63"
let test7 = "1.1.1.1,19.91. 21.63"

console.log(validIPs(test1))
console.log(validIPs(test2))
console.log(validIPs(test3))
console.log(validIPs(test4))
console.log(validIPs(test5))
console.log(validIPs(test6))
console.log(validIPs(test7))
Neil
  • 2,004
  • 3
  • 23
  • 48