-
Notifications
You must be signed in to change notification settings - Fork 9
/
is_ipv6.ts
37 lines (29 loc) · 999 Bytes
/
is_ipv6.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import type { Validity } from "../types.ts";
import { invalid } from "../utils.ts";
export function isIPv6(value: any): Validity {
const invalidResult = invalid("isIPv6", { value });
if (typeof value !== "string") {
return invalidResult;
}
const segments = value.split(":");
const invalidSegments = segments.filter(
(s) => !s.match(/^(|[0-9a-f]{1,4})$/i),
);
if (invalidSegments.length > 0) {
return invalidResult;
}
const emptySegmentsCount = segments.filter((s) => s === "").length;
const startsWithLeadingZeros = value.match(/^::/) ? true : false;
const endsWithLeadingZeros = value.match(/::$/) ? true : false;
const maxSegments = startsWithLeadingZeros || endsWithLeadingZeros ? 9 : 8;
let maxEmptySegments = 1;
if (startsWithLeadingZeros) {
maxEmptySegments += 1;
}
if (endsWithLeadingZeros) {
maxEmptySegments += 1;
}
if (segments.length > maxSegments || emptySegmentsCount > maxEmptySegments) {
return invalidResult;
}
}