Best practices
General advice for getting the most out of intl-tel-input, whether you’re using the JavaScript plugin or one of the framework components (React, Vue, Angular, Svelte).
Contents
- Load the utils module
- Store and restore numbers in E.164 format
- Validate before saving
- Enable strict mode to prevent invalid input
- Set the initial country
- Translate the UI
Load the utils module
Load utils.js to enable formatting and validation.
Store and restore numbers in E.164 format
Since the dial code is embedded in the number (e.g. "+17024181234"), you don’t need to store the country separately. To read the number out in E.164, use getNumber (or your component’s change callback / bound value). To restore it, pass the stored E.164 number as the input’s starting value on initialisation — the plugin will automatically set the country* and format the number according to your options.
*Except for some small satellite territories, which share number ranges with the main country, in which case we default to selecting the main country.
Validate before saving
Check the number is valid before storing it, and reject invalid input. Get the validity from isValidNumber (plugin) or the onChangeValidity / validityChange callback (components). Requires the utils module.
Deriving a user-facing error message
When a number is invalid, you’ll get an error code (from getValidationError for the plugin, or via the onChangeErrorCode / errorCodeChange callback for the components). Mapping the error codes to user-facing messages is left to you because the wording belongs to your app. Here is a reasonable starting point:
const getErrorMessage = (number, errorCode) => {
if (!number) return "Please enter a number";
const genericError = "Invalid number";
const { validationError } = intlTelInput.utils;
const errorMap = {
[validationError.INVALID_COUNTRY_CODE]: "Invalid dial code",
[validationError.TOO_SHORT]: "Too short",
[validationError.TOO_LONG]: "Too long",
[validationError.INVALID_LENGTH]: genericError,
};
return errorMap[errorCode] || genericError;
};
Enable strict mode to prevent invalid input
Enable strictMode to reject non-numeric characters and cap the length at the country’s max as the user types. But, importantly, make sure to pair it with some form of feedback so the rejection isn’t silent, to avoid confusion. The simplest option is to enable strictRejectAnimation for a built-in shake/flash animation. For richer feedback (e.g. a toast that explains why the input was rejected), listen for the strict:reject event (plugin) or use the equivalent onStrictReject / strictReject callback (components).
Set the initial country
If you know the user’s country, set initialCountry (e.g. "us"). If you don’t, set it to "auto" along with the geoIpLookup option to determine the country from their IP address — see example.
Translate the UI
If you know the user’s language, you can translate the country names and UI strings — see Localisation.