Back to all patterns
CIDR Notation Validation
Web & Network
Validates IPv4 CIDR notation like 192.168.1.0/24.
/^(?:(?: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]|[1-2][0-9]|3[0-2])$/How it works
CIDR (Classless Inter-Domain Routing) notation combines an IPv4 address with a prefix length (0–32) separated by a slash. This pattern validates both the IPv4 address portion and the prefix length range.
Test Cases
Should Match
- 192.168.1.0/24
- 10.0.0.0/8
- 172.16.0.0/12
Should NOT Match
- 192.168.1.0/33
- 256.0.0.0/24
- 192.168.1.0
Quick Summary
Validates IPv4 CIDR notation (address/prefix). Validates both the IPv4 address (each octet 0–255) and the prefix length (0–32). Used in firewall rules, VPC configurations, and network access control lists.
Key Takeaways
Key Takeaways
- Format: valid IPv4 address followed by /prefix (0–32)
- Prefix /0 matches all addresses; /32 matches a single host
- Does not validate whether the host bits are zero (e.g., 192.168.1.5/24 passes but is not a network address)
- For IPv6 CIDR, the prefix range is 0–128
Use Cases
When to use it
- Validating VPC CIDR blocks in cloud infrastructure forms
- Checking firewall rule inputs in network security tools
- Parsing IP allowlists and blocklists
Watch out
Common Mistakes
- Accepting /33 or higher, prefix must be 0–32 for IPv4
- Not checking that host bits are zero for network addresses, use a network library for that
FAQ
CIDR Notation Validation, Frequently Asked
What does /24 mean in CIDR notation?
/24 means the first 24 bits are the network prefix, leaving 8 bits for host addresses, 256 total addresses (254 usable).
How do I calculate the number of hosts in a CIDR block?
Hosts = 2^(32 - prefix) - 2. For /24: 2^8 - 2 = 254 usable hosts.