UNPKG

2.12 kBJavaScriptView Raw
1const v4 = '(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}';
2const v6s = '[a-fA-F\\d]{1,4}';
3const v6 = `
4(?:
5(?:${v6s}:){7}(?:${v6s}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
6(?:${v6s}:){6}(?:${v4}|:${v6s}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4
7(?:${v6s}:){5}(?::${v4}|(?::${v6s}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4
8(?:${v6s}:){4}(?:(?::${v6s}){0,1}:${v4}|(?::${v6s}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4
9(?:${v6s}:){3}(?:(?::${v6s}){0,2}:${v4}|(?::${v6s}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4
10(?:${v6s}:){2}(?:(?::${v6s}){0,3}:${v4}|(?::${v6s}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
11(?:${v6s}:){1}(?:(?::${v6s}){0,4}:${v4}|(?::${v6s}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
12(?::(?:(?::${v6s}){0,5}:${v4}|(?::${v6s}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
13)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
14`.replace(/\s*\/\/.*$/gm, '').replace(/\n/g, '').trim();
15const v46Exact = new RegExp(`(?:^${v4}$)|(?:^${v6}$)`);
16const v4exact = new RegExp(`^${v4}$`);
17const v6exact = new RegExp(`^${v6}$`);
18/**
19 * @name isIp
20 * @summary Tests if the value is a valid IP address
21 * @description
22 * Checks to see if the value is a valid IP address. Optionally check for either v4/v6
23 * @example
24 * <BR>
25 *
26 * ```javascript
27 * import { isIp } from '@polkadot/util';
28 *
29 * isIp('192.168.0.1')); // => true
30 * isIp('1:2:3:4:5:6:7:8'); // => true
31 * isIp('192.168.0.1', 'v6')); // => false
32 * isIp('1:2:3:4:5:6:7:8', 'v4'); // => false
33 * ```
34 */
35export function isIp(value, type) {
36 switch (type) {
37 case 'v4': return v4exact.test(value);
38 case 'v6': return v6exact.test(value);
39 default: return v46Exact.test(value);
40 }
41}