UNPKG

839 BJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3import ipRegex from 'ip-regex';
4
5/**
6 * @name isIp
7 * @summary Tests if the value is a valid IP address
8 * @description
9 * Checks to see if the value is a valid IP address. Optionally check for either v4/v6
10 * @example
11 * <BR>
12 *
13 * ```javascript
14 * import { isIp } from '@polkadot/util';
15 *
16 * isIp('192.168.0.1')); // => true
17 * isIp('1:2:3:4:5:6:7:8'); // => true
18 * isIp('192.168.0.1', 'v6')); // => false
19 * isIp('1:2:3:4:5:6:7:8', 'v4'); // => false
20 * ```
21 */
22export function isIp(value, type) {
23 if (type === 'v4') {
24 return ipRegex.v4({
25 exact: true
26 }).test(value);
27 } else if (type === 'v6') {
28 return ipRegex.v6({
29 exact: true
30 }).test(value);
31 }
32
33 return ipRegex({
34 exact: true
35 }).test(value);
36}
\No newline at end of file