Validation

It is important to validate any user input before saving it to your backend. The isValidNumber method provides a simple form of validation that only checks the number length, which should be sufficient for most use cases. The advantage of this simple approach is that it is much more future-proof as while countries around the world regularly update their number rules, they very rarely change their number lengths. For a more precise (and much less stable) form of validation, see Precise Validation (dangerous).

isValidNumber respects the validationNumberTypes option, which is set to ["MOBILE"] by default, meaning it will only return true for mobile numbers.

If isValidNumber returns false and you'd like more detail, you can then use the getValidationError method to get more information. This method returns an error code (integer), which you can then map to your own custom error message, as in the example below.

All validation methods require the utils script to be loaded (see the readme for instructions). The utils script contains a custom build of Google's libphonenumber library in JavaScript, which provides validation tools as well as formatting and placeholder number generation.

Demo

NOTE: by default, isValidNumber only returns true for mobile numbers. See validationNumberType option for more information.

Enter mobile 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, {
  initialCountry: "us",
  loadUtils: () => import("/intl-tel-input/js/utils.js?1733756310855"),
});

const reset = () => {
  input.classList.remove("error");
  errorMsg.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.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);