Reputation: 637
Hello I am a javascript noob and was writing a validator for an IP range. For example 1.1.1.1-2.2.2.2 is a valid range however I want to make sure that the first IP is not greater than the second IP. 2.2.2.2-1.1.1.1 should return false. What is the best strategy to go about this problem, should I try to convert each IP string to a map of integers and then compare them one by one? Should I iterate a for loop 1-4 and compare the first value before the . and then the second etc.
ipRangeValidator: function(value)
{
if (!value)
return true;
var split = value.split('-');
if (!split || split.length > 2 || split.length === 0) {
return 'Input only an IP or single IP Range';
}
var ips = [];
for (var x = 0; x < split.length; ++x) {
var ip = split[x];
if (isValidIpV6Address(ip)) {
} else if (isValidIpV4Address(ip)) {
} else {
return ip + ' is not a valid IP address';
}
ips.push(ip);
}
if (ips.length > 1) {
if(true) { //The Line I am struggling with
return 'The first IP is greater than the second IP';
}
}
return true;
}
Upvotes: 0
Views: 967
Reputation: 15530
Would something, like that work for you?
const validRange = '1.1.1.1-2.2.2.2',
invalidRange = '2.2.2.2-1.1.1.1',
anotherInvalidRange = '1.1.3.1-1.1.2.1',
invalidIp = '1.1.300.1-1.1.1.1',
isRangeValid = range => {
const [rangeStart, rangeEnd] = range.split('-'),
[s1,s2,s3,s4] = rangeStart.split('.'),
[e1,e2,e3,e4] = rangeEnd.split('.')
return [s1,s2,s3,s4].some(o => o>255 || o<0) || [e1,e2,e3,e4].some(o => o>255 || o<0) ?
'range contains invalid IP' :
s1>e1 || s2>e2 || s3>e3 || s4>e4 ?
'range start is greater than range end' :
'range is valid'
}
console.log(isRangeValid(validRange))
console.log(isRangeValid(invalidRange))
console.log(isRangeValid(anotherInvalidRange))
console.log(isRangeValid(invalidIp))
.as-console-wrapper{min-height:100%;}
Upvotes: 4
Reputation: 178026
Does this help?
const pad = (num) => String("00"+num).slice(-3);
const ipRange = rng => {
let [ip1,ip2] = rng.split("-");
ip1 = ip1.split(".").map(num => pad(num)).join('.')
ip2 = ip2.split(".").map(num => pad(num)).join('.')
return ip1>ip2;
};
console.log(
ipRange("1.1.1.1-2.2.2.2")
)
console.log(
ipRange("2.2.2.2-1.1.1.1")
)
Upvotes: 0