JAVASCRIPT
Validating IPv4 Addresses with Regular Expressions
Ensure correct IPv4 address formats with a precise regular expression in JavaScript, verifying the structure of each octet for network configurations and input.
function isValidIPv4(ipAddress) {
// Matches a valid IPv4 address format (e.g., 192.168.1.1)
// Ensures each octet is between 0 and 255.
const ipv4Regex = new RegExp(
/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
);
return ipv4Regex.test(ipAddress);
}
// Examples:
console.log(isValidIPv4("192.168.1.1")); // true
console.log(isValidIPv4("10.0.0.255")); // true
console.log(isValidIPv4("255.255.255.255"));// true
console.log(isValidIPv4("0.0.0.0")); // true
console.log(isValidIPv4("192.168.1.256"));// false (octet > 255)
console.log(isValidIPv4("192.168.1")); // false (too few octets)
console.log(isValidIPv4("invalid.ip")); // false
How it works: The `isValidIPv4` function validates if a string represents a correctly formatted IPv4 address. The regular expression is designed to match four octets, each separated by a dot. Each octet pattern `(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)` ensures that the number is between 0 and 255, covering cases for 3-digit (250-255, 200-249), 2-digit (10-99), and 1-digit (0-9) numbers. The pattern is repeated three times for the first three octets, followed by the final octet, ensuring the correct structure.