JavaScript plugin example
Single country
Even if you only need to handle numbers from a single country, the plugin still earns its keep. It provides:
- A country-specific example number for the placeholder
- Format-as-you-type
- Validation
The user can type their number in national format, and you can use getNumber to retrieve it in standardised international format for storage.
In this example we've set onlyCountries to a single country (United States), and disabled allowDropdown and showFlags. Play with these options in the Playground.
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 (United States)</label>
<input id="phone" name="phone" type="tel">
<button type="submit">Submit</button>
</form>
<span id="error-msg"></span>
JavaScript
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, {
onlyCountries: ["us"],
allowDropdown: false,
showFlags: false,
strictMode: true,
strictRejectAnimation: true,
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();
});