Single country

Even if you only need to handle numbers from a single country, the plugin can still be helpful. It can provide an example number for the placeholder, formatting as-you-type, as well as validation. The user can type their number in national format and then you can use getNumber to get the number in standardised international format to store in your database. In this example, we've set onlyCountries to a single country: United States, and we've disabled allowDropdown as well as showFlags. Play with these options on Storybook (using the React component).

Demo

Enter a US number:

✓ Valid

Markup

<input id="phone" type="tel">
<button class="button" id="btn" type="button">Validate</button>
<span id="valid-msg" class="hide">✓ Valid</span>
<span id="error-msg" class="hide"></span>

Code

const input = document.querySelector("#phone");
const button = document.querySelector("#btn");
const errorMsg = document.querySelector("#error-msg");
const validMsg = document.querySelector("#valid-msg");

// here, the index maps to the error code returned from getValidationError - see readme
const errorMap = ["Invalid number", "Invalid country code", "Too short", "Too long", "Invalid number"];

// initialise plugin
const iti = window.intlTelInput(input, {
  onlyCountries: ["us"],
  allowDropdown: false,
  showFlags: false,
  utilsScript: "/intl-tel-input/js/utils.js?1730730622316"
});

const reset = () => {
  input.classList.remove("error");
  errorMsg.innerHTML = "";
  validMsg.innerHTML = "";
  errorMsg.classList.add("hide");
  validMsg.classList.add("hide");
};

const showError = (msg) => {
  input.classList.add("error");
  errorMsg.innerHTML = msg;
  errorMsg.classList.remove("hide");
};

// on click button: validate
button.addEventListener('click', () => {
  reset();
  if (!input.value.trim()) {
    showError("Required");
  } else if (iti.isValidNumber()) {
    validMsg.innerHTML = "Valid number: " + iti.getNumber();
    validMsg.classList.remove("hide");
  } else {
    const errorCode = iti.getValidationError();
    const msg = errorMap[errorCode] || "Invalid number";
    showError(msg);
  }
});

// on keyup / change flag: reset
input.addEventListener('change', reset);
input.addEventListener('keyup', reset);