JAVASCRIPT

Validating IPv4 Addresses with Regex

Validate IPv4 addresses with a precise JavaScript regex. Ideal for web forms and data processing, ensuring adherence to the standard dotted-decimal notation (0.0.0.0 to 255.255.255.255).

function isValidIPv4Address(ip) {
  // Regex for IPv4 address validation
  // Matches numbers 0-255 separated by dots.
  const ipv4Regex = /^(?:(?: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(ip);
}

console.log("Valid IP:", isValidIPv4Address("192.168.1.1")); // true
console.log("Valid IP:", isValidIPv4Address("0.0.0.0")); // true
console.log("Valid IP:", isValidIPv4Address("255.255.255.255")); // true
console.log("Invalid IP (too high):";, isValidIPv4Address("256.0.0.0")); // false
console.log("Invalid IP (missing segment):";, isValidIPv4Address("192.168.1")); // false
console.log("Invalid IP (text):";, isValidIPv4Address("abc.def.ghi.jkl")); // false
How it works: This JavaScript function utilizes a regular expression to validate if a given string is a correctly formatted IPv4 address. The pattern `(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)` is a non-capturing group that matches any number from 0 to 255. This group is repeated exactly three times, followed by a literal dot `\.`, and then the same pattern for the final segment. The `^` and `$` anchors ensure the entire string must match the pattern.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs