JavaScript plugin example
Validation
The isValidNumber method validates a number by checking its length, which is sufficient for most use cases and more stable than precise validation since number lengths rarely change.
Validation respects the allowedNumberTypes option, which is set to ["MOBILE", "FIXED_LINE"] by default, meaning it will only consider those types of numbers as valid.
When a number fails validation, you can use getValidationError to get the error code, which you can then map to your own custom error message — see Deriving a user-facing error message.
Note: the red/green styling and warning/success icons are not part of the plugin — in this example they come from Bootstrap form validation.
Demo
Note: by default, validation only considers mobile and fixed line numbers as valid. See
allowedNumberTypes option for more information.
Html
<form id="form">
<label for="phone">Phone number</label>
<input id="phone" name="phone" type="tel">
<button type="submit">Submit</button>
</form>
<span id="error-msg"></span>
JavaScript
geoIpLookup here uses ipapi's limited free tier — for production, pick a paid plan, another provider, or roll your own.yourCodeToDeriveErrorMessage is up to you — see Deriving a user-facing error message for a worked example.import intlTelInput from "intl-tel-input";
const form = document.querySelector("#form");
const input = document.querySelector("#phone");
const errorMsg = document.querySelector("#error-msg");
const validMsg = document.querySelector("#valid-msg");
// initialise plugin
const iti = intlTelInput(input, {
initialCountry: "auto",
separateDialCode: true,
strictMode: true,
strictRejectAnimation: true,
geoIpLookup: (success, failure) => {
fetch("https://ipapi.co/json")
.then(res => res.json())
.then(data => success(data.country_code))
.catch(() => failure());
},
loadUtils: () => import("intl-tel-input/utils"),
});
// wait for utils to load before calling isValidNumber
await iti.promise;
let showValidation = false;
let submitted = false;
const updateUI = () => {
if (!showValidation) return;
const isValid = iti.isValidNumber();
let invalidMsg = "";
if (!isValid) {
const errorCode = iti.getValidationError();
invalidMsg = yourCodeToDeriveErrorMessage(input.value, errorCode);
}
errorMsg.textContent = invalidMsg;
validMsg.textContent = isValid && submitted ? `Full number: ${iti.getNumber()}` : "";
};
// on submit: validate (and show "Full number" if valid)
form.addEventListener("submit", (e) => {
e.preventDefault();
showValidation = true;
submitted = true;
updateUI();
});
// on blur: enable validation UI
input.addEventListener("blur", () => {
showValidation = true;
updateUI();
});
// while typing / pasting / changing country: remove any submitted state and update validity state
input.addEventListener("input", () => {
submitted = false;
updateUI();
});