Precise validation (advanced)
WARNING: Various countries around the world update their number rules every month, so isValidNumberPrecise will start rejecting valid numbers unless you constantly keep it up-to-date e.g. via an automated script. For this reason, we strongly recommend sticking to the standard validation method which is much more stable as it only checks number length rules, which rarely change.
isValidNumberPrecise respects the allowedNumberTypes option, which is set to ["MOBILE", "FIXED_LINE"] by default, meaning it will only return true for those types of numbers.
If isValidNumberPrecise 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.
Note: the red/green validation styling and warning/success icons in this example come from Bootstrap form validation.
Demo
NOTE: by default, isValidNumberPrecise only returns true for mobile and fixed line numbers. See allowedNumberTypes option for more information.
Html
<form id="form">
<input id="phone" type="tel">
<button type="submit">Submit</button>
</form>
<span id="error-msg"></span>
JavaScript
import intlTelInput from "intl-tel-input";
const form = document.querySelector("#form");
const input = document.querySelector("#phone");
const errorMsg = document.querySelector("#error-msg");
// initialise plugin
const iti = intlTelInput(input, {
initialCountry: "us",
loadUtils: () => import("intl-tel-input/utils"),
});
let showValidation = false;
const updateUI = () => {
if (!showValidation) return;
let invalidMsg = "";
if (!iti.isValidNumberPrecise()) {
const errorCode = iti.getValidationError();
invalidMsg = yourCodeToDeriveErrorMessage(input.value(), errorCode);
}
errorMsg.textContent = invalidMsg;
};
// on submit: enable validation UI
form.addEventListener("submit", (e) => {
e.preventDefault();
showValidation = true;
updateUI();
});
// on blur: enable validation UI
input.addEventListener("blur", () => {
showValidation = true;
updateUI();
});
// while typing / pasting / changing country: update validity state
input.addEventListener("input", updateUI);
input.addEventListener("countrychange", updateUI);