• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

liuarui / easyutils / 10768224429

09 Sep 2024 07:04AM UTC coverage: 96.284% (-1.0%) from 97.268%
10768224429

push

github

liuarui
fix(validate): fix ipv6

88 of 94 branches covered (93.62%)

Branch coverage included in aggregate %.

37 of 39 new or added lines in 1 file covered. (94.87%)

197 of 202 relevant lines covered (97.52%)

13.7 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.48
/src/validate/validateIP.ts
1
// 正则表达式用于验证IPv4地址
2✔
2
const ipv4Regex = /^((25[0-5]|2[0-4]\d|1?\d\d?)\.){3}(25[0-5]|2[0-4]\d|1?\d\d?)$/;
2✔
3

2✔
4
export function validateIPV4(ip: string) {
2✔
5
    if (ipv4Regex.test(ip)) {
42✔
6
        return true;
12✔
7
    }
12✔
8
    return false;
30✔
9
}
30✔
10

2✔
11
export function validateIPV6(ip: string): boolean {
2✔
12
    if (!ip || typeof ip !== 'string') return false;
56!
13

56✔
14
    // IPv6 should not have more than one '::'
56✔
15
    if (ip.split('::').length > 2) return false;
56✔
16

44✔
17
    // Split the address into segments
44✔
18
    const segments = ip.split(':');
44✔
19

44✔
20
    // Handle '::' cases
44✔
21
    if (ip.includes('::')) {
56✔
22
        // Handle leading '::' or trailing '::'
18✔
23
        const doubleColonIndex = segments.indexOf('');
18✔
24
        if (doubleColonIndex === 0 || doubleColonIndex === segments.length - 1) {
18✔
25
            segments.splice(doubleColonIndex, 1); // Remove empty part caused by leading/trailing '::'
12✔
26
        }
12✔
27

18✔
28
        const partsBeforeDoubleColon = segments.slice(0, doubleColonIndex);
18✔
29
        const partsAfterDoubleColon = segments.slice(doubleColonIndex);
18✔
30

18✔
31
        // At most there can be 7 parts before and after '::'
18✔
32
        if (partsBeforeDoubleColon.length + partsAfterDoubleColon.length > 7) {
18!
NEW
33
            return false;
×
NEW
34
        }
×
35
    } else if (segments.length !== 8) {
56✔
36
        // If there's no '::' and the segments are not exactly 8, it's invalid
18✔
37
        return false;
18✔
38
    }
18✔
39

26✔
40
    const hexRegex = /^[0-9a-fA-F]{1,4}$/;
26✔
41
    for (const segment of segments) {
56✔
42
        if (segment === '') continue; // Skip empty segments caused by '::'
108✔
43
        if (!hexRegex.test(segment)) {
108✔
44
            return false;
6✔
45
        }
6✔
46
    }
108✔
47

20✔
48
    return true;
20✔
49
}
20✔
50

2✔
51
export function validateIP(ip: string) {
2✔
52
    if (validateIPV4(ip) || validateIPV6(ip)) {
28✔
53
        return true;
12✔
54
    }
12✔
55
    return false;
16✔
56
}
16✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc