/*
- check ip address cidr validation
*/
function checkIpAddress(ip: string) {
const cidr = ip.split(/[/]/);
if ((cidr.length < 3)){
const cidrExist = cidr[1] !== undefined ? true : false;
const cidrValue = parseInt(cidr[1])
const partsV4 = cidr[0].split(/[.]/);
const partsV6 = cidr[0].split(/[:]/);
if (partsV4.length === 4) {
// Check IPv4 parts
for (const part of partsV4) {
const num = parseInt(part);
if (isNaN(num) || num < 0 || num > 255) {
return false;
}
}
if ((cidrExist) && ((isNaN(cidrValue)) || (cidrValue < 1) || (cidrValue > 32))){
return false;
}
return true;
}
else if ((partsV6.length > 2) && (partsV6.length <= 8)) {
// Check IPv6 parts
for (const part of partsV6) {
if (!/^[0-9a-fA-F]{0,4}$/.test(part)) {
return false;
}
}
if ((cidrExist) && ((isNaN(cidrValue)) || (cidrValue < 1) || (cidrValue > 128))){
return false;
}
return true;
}
}
return false;
}
this function to validate a IP address with/not cidr.
for the ipv6 is the regex is correct or maybe someone have a more performant regex to check the IPV6?
New contributor
Moomen Oueslati is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.