Emmanuel Akinfulubi

JavaScriptRegular expressions

Validate an IPv4 address in JavaScript

Advanced · 3 min read

An IPv4 address is the four-number label a computer uses on a network, like 192.168.1.1 on a home router or 8.8.8.8 for a public DNS server. Network settings pages, firewall rules and server config forms all need to check that what you typed is a real address before saving it.

In this tutorial you will write isIPv4. You will start with the pattern almost everyone writes first, see it accept 999.999.999.999, and then fix it. You will also write a second version with no regex at all, which is easier to trust. You need to know /.../.test(), ^, $ and \d. Everything else is explained as we go.

The rules of an IPv4 address

An address is four numbers separated by dots. Each number is called an octet and must be from 0 to 255. Two more rules:

  • exactly four parts, no more and no fewer
  • no leading zeros, so 01 is not allowed (some tools used to read a leading zero as an octal number, so 010 could mean 8)

Counting with {1,3}

In a pattern, {1,3} after something means "between one and three of it". \d{1,3} is one to three digits:

JavaScript

console.log(/^\d{1,3}$/.test('42'));   // true
console.log(/^\d{1,3}$/.test('1234')); // false

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

7 Validate an IP address

hard

Check whether a string is an IPv4 address. The obvious pattern accepts 999.999.999.999; make one that does not.

Stuck? Three hints, smallest first
  1. 1. \d{1,3} allows 0 to 999. The valid range is 0 to 255.
  2. 2. Match the range in pieces: 25[0-5], 2[0-4]\d, 1\d\d, [1-9]?\d.
  3. 3. Leading zeros should be refused: 01.1.1.1 is ambiguous, and historically read as octal.

Step 1: the pattern everyone writes first

Four groups of one to three digits with dots between. A dot must be written \., because a plain . in a pattern means "any character":

JavaScript

const NAIVE = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
console.log(NAIVE.test('192.168.1.1'));     // true
console.log(NAIVE.test('999.999.999.999')); // true, but 999 is over 255
console.log(NAIVE.test('01.1.1.1'));        // true, but 01 has a leading zero

\d{1,3} means 0 to 999. The real range is 0 to 255, and a character class can't say "up to 255" directly.

Step 2: spell out 0 to 255 by shape

The trick is to split the range into pieces whose digits you can describe, and join them with | (which means "or"):

One octet

25[0-5]    250 to 255
2[0-4]\d   200 to 249
1\d\d      100 to 199
[1-9]?\d   0 to 99

The last piece needs a closer look. [1-9]? is an optional first digit that can't be 0, followed by one digit. So it matches 7 and 42, but not 07. That is what refuses leading zeros:

Step 2

const OCTET = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;
console.log(OCTET.test('255')); // true
console.log(OCTET.test('256')); // false
console.log(OCTET.test('0'));   // true
console.log(OCTET.test('07'));  // false

Step 3: repeat the octet four times

We need octet, then three times "dot and octet". {3} repeats a group exactly three times. Writing the octet once as a string and building the pattern with new RegExp saves typing it four times. Inside a string a backslash is written twice, so \\d becomes \d in the pattern:

Step 3

const OCTET = '(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)';
const IPV4 = new RegExp(`^${OCTET}(\\.${OCTET}){3}$`);
const isIPv4 = (value) => typeof value === 'string' && IPV4.test(value);
console.log(isIPv4('192.168.1.1'));     // true
console.log(isIPv4('999.999.999.999')); // false
console.log(isIPv4('1.2.3'));           // false
console.log(isIPv4('1.2.3.4.5'));       // false
console.log(isIPv4(19216811));          // false: not a string

The typeof check refuses numbers and other values before the pattern even runs.

Step 4: the same check without a regex

When the rule is a number range, comparing numbers is often clearer. Split on the dots, then check each part:

Step 4

function isIPv4Plain(value) {
  if (typeof value !== 'string') return false;
  const parts = value.split('.');
  if (parts.length !== 4) return false;
  return parts.every((p) =>
    /^\d+$/.test(p) &&
    String(Number(p)) === p &&
    Number(p) <= 255);
}
console.log(isIPv4Plain('255.255.255.255')); // true
console.log(isIPv4Plain('256.1.1.1'));       // false
console.log(isIPv4Plain('01.1.1.1'));        // false
console.log(isIPv4Plain('1.1.1.-1'));        // false

Each line of the every check does one job. /^\d+$/ allows digits only, which refuses -1 and empty parts. String(Number(p)) === p catches leading zeros, because Number('01') is 1, and '1' is not '01'. The last line enforces the 255 limit.

The full solution

The panel runs a list of addresses through the naive pattern and the correct one side by side. Press Run to see exactly where they disagree. The checks also confirm the plain version agrees with the pattern on every case.

The answer

// The pattern everyone writes first. It accepts 999.999.999.999.
const NAIVE = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;

/* One octet, 0 to 255, with no leading zeros:
     25[0-5]    250-255
     2[0-4]\d   200-249
     1\d\d      100-199
     [1-9]?\d   0-99, and the optional first digit forbids "01"        */
const OCTET = '(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)';
const IPV4 = new RegExp(`^${OCTET}(\\.${OCTET}){3}$`);

const isIPv4 = (value) => typeof value === 'string' && IPV4.test(value);

// Without a regex at all, which is easier to read and to be sure of.
function isIPv4Plain(value) {
  if (typeof value !== 'string') return false;
  const parts = value.split('.');
  if (parts.length !== 4) return false;
  return parts.every((p) =>
    /^\d+$/.test(p) &&                       // digits only
    String(Number(p)) === p &&                // no leading zeros
    Number(p) <= 255);
}

const cases = ['192.168.1.1', '255.255.255.255', '0.0.0.0', '8.8.8.8',
  '999.999.999.999', '256.1.1.1', '1.2.3', '1.2.3.4.5', '01.1.1.1', '1.1.1.-1', '', 'abc'];

for (const ip of cases) {
  console.log(JSON.stringify(ip).padEnd(20), 'naive:', String(NAIVE.test(ip)).padEnd(6), 'correct:', isIPv4(ip));
}

Output


      
19 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 19 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

19 checks

test('a normal address passes', isIPv4('192.168.1.1'), true);
test('the maximum passes', isIPv4('255.255.255.255'), true);
test('all zeros passes', isIPv4('0.0.0.0'), true);
test('the naive pattern accepts nonsense', NAIVE.test('999.999.999.999'), true);
test('the correct one does not', isIPv4('999.999.999.999'), false);
test('256 is one too many', isIPv4('256.1.1.1'), false);
test('but 255 is fine', isIPv4('255.1.1.1'), true);
test('three parts is not enough', isIPv4('1.2.3'), false);
test('five is too many', isIPv4('1.2.3.4.5'), false);
test('a leading zero is refused', isIPv4('01.1.1.1'), false);
test('though the naive pattern allows it', NAIVE.test('01.1.1.1'), true);
test('a negative number is refused', isIPv4('1.1.1.-1'), false);
test('an empty string is refused', isIPv4(''), false);
test('letters are refused', isIPv4('abc'), false);
test('a number rather than a string is refused', isIPv4(19216811), false);
test('the plain version agrees on every case', cases.every((ip) => isIPv4(ip) === isIPv4Plain(ip)), true);
test('and the two disagree with the naive one', cases.some((ip) => NAIVE.test(ip) !== isIPv4(ip)), true);
test('249 is in the 2[0-4]d branch', isIPv4('249.0.0.0'), true);
test('and 199 in the 1dd branch', isIPv4('199.0.0.0'), true);

This is the clearest example in the section of a pattern that looks right and is not. d{1,3} means "one to three digits", which is 0 to 999, and the assertion confirms the naive pattern happily accepts 999.999.999.999. Matching a numeric range in a regex means enumerating it by shape: 25[0-5], then 2[0-4]d, then 1dd, then [1-9]?d. The optional first digit in that last branch is what refuses 01.

Leading zeros are worth refusing rather than tolerating. 01.1.1.1 is ambiguous — some networking tools historically read a leading zero as octal, so 010 meant 8 — and accepting it means two different strings for the same address.

The regex-free version is shorter, obviously correct, and gives a better error message. Reach for a pattern when the shape is the rule; when the rule is a numeric range, compare numbers. Note also that none of this covers IPv6, which needs a genuinely different approach.

Common mistakes

  • Using \d{1,3} for each part. It allows anything up to 999.
  • Writing . instead of \.. An unescaped dot matches any character, so 1a2b3c4 would pass the naive pattern.
  • Allowing leading zeros. 01.1.1.1 and 1.1.1.1 then count as two different spellings of the same address.

Try it yourself

  1. Write isPrivate(ip) that returns true for addresses starting with 10. or 192.168..
  2. Change isIPv4Plain to return the reason it failed, such as 'part 2 is over 255'.
  3. Write toNumber(ip) that turns '1.2.3.4' into one number: ((1 * 256 + 2) * 256 + 3) * 256 + 4.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.