Coding Challenge Practice - Question 119
The task is to implement a function that validates IPv4 and IPv6 IP addresses. The boilerplate code function isValidIP(str) { // your code here } A valid IPv4 address should be in 4 parts, separated by ".", and should contain digits between 0 and 255, with no number having a leading zero. Create a function to validate those parameters function isValidIPv4(ip) { } Each part should be separated by "." const parts = ip.split("."); There must be exactly 4 parts if(parts.length !== 4) return false; If the number is less than zero or greater than 255, it is not a valid IPv4 address. The number should also not have a leading 0. for (const part of parts) { if (!/^\d+$/.test(part)) return false; if (part.length > 1 && part[0] === '0') return false; const num = Number(part); if (num < 0 || num > 255) return false; } return true; } The complete function to validate an IPv4 address function isValidIPv4(ip) { const parts = ip.split('.'); if (parts.length !== 4) return false; for (const part of part
Continue reading on Dev.to Beginners
Opens in a new tab



