Emmanuel Akinfulubi

JavaScriptRegular expressions

Validate a domain name with regex in JavaScript

Intermediate · 3 min read

A domain name is the readable address of a website: example.com, sub.example.co.uk. Hosting dashboards, email settings and "add your custom domain" forms all check that what you typed is a valid domain before trying to use it.

Domain names have precise rules about length and which characters can go where. In this tutorial you will turn each rule into a small piece of pattern, then combine them. You will also see a rule that is easier to check with plain code than with a regex. You need to know /.../.test(), ^, $ and character classes. Groups and building a pattern from strings are explained as we go.

The rules

A domain is made of labels separated by dots. In sub.example.com the labels are sub, example and com.

  • Each label is 1 to 63 characters: letters, digits and dashes.
  • A label can't start or end with a dash.
  • The last label, the top-level domain (TLD) like com or uk, is letters only, at least two.
  • There must be at least two labels, and the whole name is at most 253 characters.

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

18 Does the value look like a domain?

fair

Check whether a string is a domain name. Labels are limited in length and in what characters they may start and end with.

Stuck? Three hints, smallest first
  1. 1. Each label is 1 to 63 characters, letters digits and dashes, and cannot start or end with a dash.
  2. 2. The whole name is at most 253 characters, and needs at least two labels.
  3. 3. The trailing label is the TLD and is letters only, at least two of them.

Step 1: one label

A label must start with a letter or digit. Then, if it is longer than one character, it has up to 61 characters of letters, digits or dashes, and ends with a letter or digit again. 1 + 61 + 1 = 63, the limit:

One label

[A-Za-z0-9]                 first character, no dash
(?:[A-Za-z0-9-]{0,61}       up to 61 middle characters, dashes allowed
[A-Za-z0-9])?               last character, no dash

(?: ... ) is a group that bundles without capturing, and the ? after it makes the whole tail optional. That is what allows a one-character label like a:

Step 1

const LABEL = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/;
console.log(LABEL.test('example')); // true
console.log(LABEL.test('my-site')); // true
console.log(LABEL.test('a'));       // true
console.log(LABEL.test('-site'));   // false
console.log(LABEL.test('site-'));   // false
console.log(LABEL.test('a'.repeat(63))); // true
console.log(LABEL.test('a'.repeat(64))); // false

'a'.repeat(63) builds a string of 63 letters, a handy way to test the exact limit.

Step 2: build the full pattern from pieces

Keep the label as a string so it can be reused. A domain is "one or more labels, each followed by a dot", then the TLD. [A-Za-z]{2,} means "two or more letters". new RegExp turns the string into a pattern. Inside a template string, \\. becomes \., a real dot:

Step 2

const LABEL = '[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?';
const TLD = '[A-Za-z]{2,}';
const DOMAIN = new RegExp(`^(?:${LABEL}\\.)+${TLD}$`);
console.log(DOMAIN.test('example.com'));           // true
console.log(DOMAIN.test('my-site.example.co.uk')); // true
console.log(DOMAIN.test('example'));               // false: one label
console.log(DOMAIN.test('example..com'));          // false: empty label
console.log(DOMAIN.test('example.c'));             // false: one-letter TLD
console.log(DOMAIN.test('192.168.1.1'));           // false: TLD is digits

The + after the group demands at least one "label and dot" before the TLD, which is what refuses a single label.

Step 3: the total length

"At most 253 characters" is awkward to say inside the pattern, because the labels already have their own lengths. It is one line of ordinary code instead:

Step 3

const LABEL = '[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?';
const TLD = '[A-Za-z]{2,}';
const DOMAIN = new RegExp(`^(?:${LABEL}\\.)+${TLD}$`);
const isDomain = (value) =>
  typeof value === 'string' &&
  value.length <= 253 &&
  DOMAIN.test(value);
const long = ('a'.repeat(60) + '.').repeat(5) + 'com';
console.log(long.length);     // 308
console.log(isDomain(long));  // false
console.log(isDomain('a.co')); // true

Every label in long is fine on its own, but the whole name is too long. Validating often means a pattern plus a couple of normal checks.

Step 4: two edge cases to know

JavaScript

const LABEL = '[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?';
const DOMAIN = new RegExp(`^(?:${LABEL}\\.)+[A-Za-z]{2,}$`);
console.log(DOMAIN.test('example.com.'));       // false
console.log(DOMAIN.test('xn--80ak6aa92e.com')); // true

A trailing dot, example.com., is technically allowed in DNS, but in a form it is almost always a typo, so refusing it is usually what you want. Domains in other alphabets reach code in a converted form called punycode, which starts with xn-- and uses only letters, digits and dashes. That form passes. The original non-Latin text would not.

The full solution

The panel runs a list of good and bad domains, including a 64-character label and a name over 253 characters. Press Run and check that 63 characters pass while 64 fail.

The answer

/* One label: starts and ends with a letter or digit, up to 61 of anything
   allowed in between, so 1 to 63 characters in total. */
const LABEL = '[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?';
const TLD = '[A-Za-z]{2,}';
const DOMAIN = new RegExp(`^(?:${LABEL}\\.)+${TLD}$`);

const isDomain = (value) =>
  typeof value === 'string' &&
  value.length <= 253 &&
  DOMAIN.test(value);

const cases = [
  'example.com', 'sub.example.com', 'a.co', 'my-site.example.co.uk',
  'xn--80ak6aa92e.com',           // punycode, a real internationalised domain
  'example', '-example.com', 'example-.com', 'exa mple.com',
  'example..com', '.example.com', 'example.c', 'example.com.', '',
  `${'a'.repeat(64)}.com`,        // a label over 63 characters
  `${'a'.repeat(60)}.com`,
];

for (const d of cases) {
  console.log(JSON.stringify(d).slice(0, 30).padEnd(32), isDomain(d));
}
console.log('a 253-character name:', isDomain(('a'.repeat(49) + '.').repeat(5) + 'com'));

Output


      
21 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 21 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

21 checks

test('a two-label domain passes', isDomain('example.com'), true);
test('a subdomain passes', isDomain('sub.example.com'), true);
test('the shortest sensible form', isDomain('a.co'), true);
test('dashes inside a label are fine', isDomain('my-site.example.co.uk'), true);
test('a punycode domain passes', isDomain('xn--80ak6aa92e.com'), true);
test('digits in a label are fine', isDomain('9ja.example.com'), true);
test('a single label is not a domain', isDomain('example'), false);
test('a leading dash is refused', isDomain('-example.com'), false);
test('a trailing dash is refused', isDomain('example-.com'), false);
test('a space is refused', isDomain('exa mple.com'), false);
test('an empty label is refused', isDomain('example..com'), false);
test('a leading dot is refused', isDomain('.example.com'), false);
test('a one-letter TLD is refused', isDomain('example.c'), false);
test('a trailing dot is refused by this pattern', isDomain('example.com.'), false);
test('an empty string is refused', isDomain(''), false);
test('a 64-character label is too long', isDomain('a'.repeat(64) + '.com'), false);
test('60 characters is fine', isDomain('a'.repeat(60) + '.com'), true);
test('and exactly 63 is the limit', isDomain('a'.repeat(63) + '.com'), true);
test('a name over 253 characters is refused', isDomain(('a'.repeat(60) + '.').repeat(5) + 'com'), false);
test('a numeric TLD is refused', isDomain('example.123'), false);
test('but an IP address is not a domain either', isDomain('192.168.1.1'), false);

The label pattern [A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])? encodes three rules at once: a label starts with a letter or digit, ends with one, and is at most 63 characters. Counting them: 1 + 61 + 1. The optional group is what allows a single-character label. The assertions check 63 passes and 64 fails, because the arithmetic is the sort of thing that is off by one when written from memory.

The 253-character total cannot be expressed in the pattern usefully, so it is a separate length check — a reminder that "validate with a regex" often means "regex plus a couple of ordinary conditions".

Two honest limits. A trailing dot, as in example.com., is technically valid and denotes the root; this pattern rejects it, which is usually what you want in a form. And internationalised domains reach this code already converted to punycode (xn--…), so a name in Arabic or Chinese script will not match unless you convert it first.

Common mistakes

  • Allowing dashes at the ends of a label. -example.com looks close to right, but is invalid. The first and last characters must be letters or digits.
  • Forgetting the escaped dot. In a string, write \\. so the pattern gets \.. A plain . means "any character".
  • Squeezing every rule into the pattern. The 253-character limit is clearer as value.length <= 253.

Try it yourself

  1. Allow an optional trailing dot by adding \\.? before the $.
  2. Write tldOf(domain) that returns the last label, so 'example.co.uk' gives 'uk'.
  3. Make the pattern case-insensitive with the i flag and shorten each class to [a-z0-9].

Keep practising

Newsletter

New writing, when it lands.

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