REGEXVAULTv2.0
Web & Network/IPv4
Verified Safe

IPv4 with CIDR Notation Regex for JavaScript

/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\/(?:3[0-2]|[12][0-9]|[0-9])$/

What this pattern does

Validating IPv4 addresses with CIDR notation in JavaScript requires a robust regular expression, and this one delivers. It accurately parses IPv4 addresses alongside their associated network prefix lengths. This pattern is ideal for use cases such as network configuration validation or input sanitization in web applications. Developers can readily incorporate this pattern into JavaScript projects for front-end or back-end data validation.

Javascript Implementation

Javascript
// IPv4 with CIDR Notation
// ReDoS-safe | RegexVault — Web & Network > IPv4

const ipv4WithCidrNotationRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\\/(?:3[0-2]|[12][0-9]|[0-9])$/;

function validateIpv4WithCidrNotation(input: string): boolean {
  return ipv4WithCidrNotationRegex.test(input);
}

// Example
console.log(validateIpv4WithCidrNotation("192.168.0.0/24")); // true

Test Cases

Matches (Valid)
Rejects (Invalid)
192.168.0.0/24192.168.1.1/33
10.0.0.0/8256.0.0.0/24
0.0.0.0/0192.168.1/24
255.255.255.255/32192.168.0.0/
172.16.0.0/12192.168.0.0

When to use this pattern

ReDoS vulnerabilities pose a significant threat to JavaScript applications, potentially leading to denial-of-service. Without a ReDoS-safe regex, an attacker can craft malicious input, causing excessive backtracking in the JavaScript engine and consuming significant CPU resources. Deploy this verified pattern confidently within a Node.js server or a browser-based form validator, knowing it has been scrutinized for production readiness.

Common Pitfalls

Using [0-9]{1,2} for the prefix allows /99. Always use the bounded alternation.

Technical Notes

Prefix length alternatives: 3[0-2] covers 30–32, [12][0-9] covers 10–29, [0-9] covers 0–9. Combined this gives 0–32 exactly.

Have a pattern that belongs in the vault?

Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.

Submit a Pattern