isValidIPv4
Checks if a string is a valid IPv4 address.
1/**
2 * Checks if a string is a valid IPv4 address.
3 *
4 * @param ip - The IPv4 address to validate.
5 * @returns True if the input is a valid IPv4 address, false otherwise.
6 */
7export function isValidIPv4(ip: string): boolean {
8 const segments = ip.split('.');
9 if (segments.length !== 4) return false;
10
11 return segments.every(seg => {
12 if (!/^\d+$/.test(seg)) return false;
13 const num = Number(seg);
14 return num >= 0 && num <= 255 && String(num) === seg;
15 });
16}
Strict Segment Validation
Ensures exactly four numeric segments separated by dots, adhering to the IPv4 standard.
Range Safety
Validates that each segment is within the 0–255 range, preventing invalid octet values.
No Leading Zeros
Rejects segments like
'01'
or'001'
, which are technically ambiguous or invalid in strict IPv4 notation.Regex-Free Per-Segment Check
Avoids full-string regex complexity by evaluating segments individually for better readability and control.
Tests | Examples
1test('valid IPv4 addresses', () => {
2 expect(isValidIPv4('192.168.0.1')).toBe(true);
3 expect(isValidIPv4('0.0.0.0')).toBe(true);
4 expect(isValidIPv4('255.255.255.255')).toBe(true);
5});
6
7test('invalid IPv4 addresses - out of range', () => {
8 expect(isValidIPv4('256.100.50.25')).toBe(false);
9 expect(isValidIPv4('192.168.0.999')).toBe(false);
10});
11
12test('invalid IPv4 addresses - wrong segment count', () => {
13 expect(isValidIPv4('192.168.1')).toBe(false);
14 expect(isValidIPv4('10.0.0.1.2')).toBe(false);
15});
16
17test('invalid IPv4 addresses - non-numeric', () => {
18 expect(isValidIPv4('abc.def.ghi.jkl')).toBe(false);
19 expect(isValidIPv4('123.456.78.90a')).toBe(false);
20});
21
22test('invalid IPv4 addresses - leading zeroes', () => {
23 expect(isValidIPv4('01.02.03.04')).toBe(false);
24});
Common Use Cases
Form Input Validation
Validate user-provided IP addresses in network configuration tools or admin panels.
Firewall or Access Control Lists
Ensure IP rules and filters only accept valid IPv4 addresses.
Logging and Monitoring Systems
Sanitize or validate source IP addresses before processing or storing logs.
Client-Side Network Utilities
Validate IPs in diagnostic tools or widgets before sending them to backend services.