简体   繁体   English

在不使用正则表达式的情况下验证由逗号分隔的多个 IP 地址

[英]Validate multiple IP addresses separated by a comma without using regex

(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:给定一个 textarea 字段,用户可以在其中输入多个 IP 地址作为逗号分隔的字符串,使用 JavaScript,验证所有这些逗号分隔的 IP 地址的最佳方法是什么,例如:

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.我显然需要测试有效的 IP 范围以及三个点和四个数字。

I would prefer a solution that doesn't use regex.我更喜欢不使用正则表达式的解决方案。

You can split each ip and check if the numbers are valid.您可以拆分每个 ip 并检查数字是否有效。 Also you can check if the dots (.) are 4.您也可以检查点 (.) 是否为 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.当然,您可以做相反的事情,只获取有效的 IP 地址。

Example例子

with String.prototype.split and Array.prototype.every使用String.prototype.splitArray.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

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); } });

Using split , map , and reduce .使用splitmapreduce

  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(".")拆分为二维数组,其中第一维是split(",")的结果,第二维是map第一维和split(".")
  2. reduce each dimension where the first dimension is used to check the length of the second dimension. reduce每个维度,其中第一个维度用于检查第二个维度的length 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然后,检查第二个数组中的每个值是否是 0-255 范围内的有效正整数(在此问题的帮助下)

This method returns false if there are spaces.如果有空格,此方法返回false

 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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