Validation
It is important to validate any user input before saving it to your backend. With International Telephone Input, you can use the isValidNumber
method, which returns true or false. If it 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.
Both of these methods require the utils script to be loaded, which can be done by specifying the utilsScript
option when initialising the plugin. The utils script contains a custom build of Google's libphonenumber library in JavaScript, which provides comprehensive phone number validation tools.
Demo
✓ ValidMarkup
<input id="phone" type="tel">
<span id="valid-msg" class="hide">✓ Valid</span>
<span id="error-msg" class="hide"></span>
Code
const input = document.querySelector("#phone");
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, {
utilsScript: "/intl-tel-input/js/utils.js?1684676252775"
});
const reset = () => {
input.classList.remove("error");
errorMsg.innerHTML = "";
errorMsg.classList.add("hide");
validMsg.classList.add("hide");
};
// on blur: validate
input.addEventListener('blur', () => {
reset();
if (input.value.trim()) {
if (iti.isValidNumber()) {
validMsg.classList.remove("hide");
} else {
input.classList.add("error");
const errorCode = iti.getValidationError();
errorMsg.innerHTML = errorMap[errorCode];
errorMsg.classList.remove("hide");
}
}
});
// on keyup / change flag: reset
input.addEventListener('change', reset);
input.addEventListener('keyup', reset);