CIDR Notation (IPv4) Regex for JavaScript
/^(?:(?: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]?)\/(?:[0-9]|[12][0-9]|3[0-2])$/What this pattern does
This page provides a comprehensive, battle-tested regular expression for matching cidr notation (ipv4), ported and verified for JavaScript. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your JavaScript project — whether you're validating in an Express middleware, a Next.js API route, or a client-side form.
Javascript Implementation
// CIDR Notation (IPv4)
// ReDoS-safe | RegexVault — Security > Network Security
const cidrNotationIpv4Regex = /^(?:(?: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]?)\\/(?:[0-9]|[12][0-9]|3[0-2])$/;
function validateCidrNotationIpv4(input: string): boolean {
return cidrNotationIpv4Regex.test(input);
}
// Example
console.log(validateCidrNotationIpv4("192.168.1.0/24")); // trueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
192.168.1.0/24 | 192.168.1.0/33 |
10.0.0.0/8 | 192.168.1.0/-1 |
172.16.0.0/12 | 192.168.1.0 |
0.0.0.0/0 | 256.0.0.0/8 |
1.2.3.4/32 | 192.168.1.0/24/extra |
When to use this pattern
This pattern is drawn from the Security > Network Security category and carries a ReDoS-safe certification. That matters for JavaScript developers because especially critical in long-running Node.js event loops where a ReDoS vulnerability can block the entire process. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
0.0.0.0/0 (any IP) in a security group rule exposes a service to the entire internet. 0.0.0.0/0 in outbound rules allows all outbound traffic. Review CIDR rules regularly in cloud security groups.
Technical Notes
/0 = all IPs (default route), /32 = single host. Subnets should have a host part of all zeros for canonical CIDR notation (192.168.1.0/24, not 192.168.1.5/24). Common in firewall rules, security groups, and IP allowlists.
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