Vanilla JavaScript Projects

Project 67, Forms and input

Phone Input with Country Codes

Let people type a phone number the way they know it. The field adds the country code, formats the number and hands your server one clean value.

+8801712 345678
Main API
Intl.DisplayNames
Output
E.164 format
Dependencies
None
Your browser
Checking

Enter a phone number

Pick a country or type to search. The number is formatted as you type and checked for length. The clean value is shown below.

Country
Send to server
-

How it works

  1. Country data in one listEach country has an ISO code, dial code, a display mask and the expected number of digits. Names come from Intl.DisplayNames in the visitor's language.
  2. Format as you typeOnly digits are kept, a leading 0 is dropped, and the mask adds spaces and brackets in the right places.
  3. Send one clean valueThe server gets the number in E.164 format: a plus sign, the dial code and the digits, with no spaces.
const names = new Intl.DisplayNames(["en"], { type: "region" });
names.of("BD");                           // "Bangladesh"

function format(digits, mask) {           // mask like "####-######"
  let out = "", i = 0;
  for (const ch of mask) {
    if (i >= digits.length) break;
    out += ch === "#" ? digits[i++] : ch;
  }
  return out;
}
const e164 = "+" + country.dial + digits; // "+8801712345678"