Skip to content

Commit 2ccaff9

Browse files
Regular Expression - IPv6 Address (#2031)
* Create script.js * Create README.md
1 parent 192e0f0 commit 2ccaff9

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# IPv6 Address Validator
2+
3+
This snippet validates **IPv6 addresses** in both full and compressed formats using JavaScript regex.
4+
5+
### Features
6+
- Supports full and shortened IPv6 formats (`::` compression)
7+
- Validates loopback (`::1`) and link-local (`fe80::`) addresses
8+
- Rejects invalid hex groups and multiple `::`
9+
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// IPv6 Address Validator
2+
// This regex validates both full and compressed IPv6 address formats, including shorthand "::" notation.
3+
4+
const ipv6Regex =
5+
/^(?:(([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:)|(([0-9A-Fa-f]{1,4}:){1,6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,5}(:[0-9A-Fa-f]{1,4}){1,2})|(([0-9A-Fa-f]{1,4}:){1,4}(:[0-9A-Fa-f]{1,4}){1,3})|(([0-9A-Fa-f]{1,4}:){1,3}(:[0-9A-Fa-f]{1,4}){1,4})|(([0-9A-Fa-f]{1,4}:){1,2}(:[0-9A-Fa-f]{1,4}){1,5})|([0-9A-Fa-f]{1,4}:((:[0-9A-Fa-f]{1,4}){1,6}))|(:((:[0-9A-Fa-f]{1,4}){1,7}|:)))(%.+)?$/;
6+
7+
function validateIPv6(address) {
8+
return ipv6Regex.test(address);
9+
}
10+
11+
// Example usage:
12+
console.log(validateIPv6("2001:0db8:85a3:0000:0000:8a2e:0370:7334")); // true (full)
13+
console.log(validateIPv6("2001:db8:85a3::8a2e:370:7334")); // true (compressed)
14+
console.log(validateIPv6("::1")); // true (loopback)
15+
console.log(validateIPv6("fe80::")); // true (link-local)
16+
console.log(validateIPv6("1234:5678:9abc:def0:1234:5678:9abc:defg")); // false (invalid hex)
17+
console.log(validateIPv6("2001::85a3::7334")); // false (double compression)

0 commit comments

Comments
 (0)