intl-tel-input
A JavaScript plugin for entering and validating international telephone numbers. Now includes React and Vue components.
Top Related Projects
Cross-browser QRCode generator for javascript
Google's common Java, C++ and JavaScript library for parsing, formatting, and validating international phone numbers.
PHP version of Google's phone number handling library
Google's common JavaScript library
Quick Overview
intl-tel-input is a JavaScript plugin for entering and validating international telephone numbers. It adds a flag dropdown to any input, detects the user's country, displays a relevant placeholder and provides formatting/validation methods.
Pros
- Easy integration with existing forms and input fields
- Automatic country detection based on user's IP address
- Extensive customization options and styling flexibility
- Comprehensive validation and formatting features
Cons
- May increase page load time due to additional resources
- Requires maintenance to keep country codes and formatting rules up-to-date
- Can be overkill for simple forms or applications with limited international scope
Code Examples
- Basic initialization:
const input = document.querySelector("#phone");
window.intlTelInput(input, {
utilsScript: "path/to/utils.js"
});
- Getting the full international number:
const iti = window.intlTelInput(input);
const number = iti.getNumber();
console.log(number); // e.g. "+1 (702) 123-4567"
- Custom country prioritization:
window.intlTelInput(input, {
preferredCountries: ['us', 'gb', 'ca']
});
- Validation on form submission:
form.addEventListener('submit', function(e) {
e.preventDefault();
if (iti.isValidNumber()) {
console.log("Valid number: " + iti.getNumber());
} else {
console.log("Invalid number");
}
});
Getting Started
- Include the CSS and JavaScript files in your HTML:
<link rel="stylesheet" href="path/to/intlTelInput.css">
<script src="path/to/intlTelInput.min.js"></script>
- Add an input element to your HTML:
<input id="phone" type="tel">
- Initialize the plugin:
const input = document.querySelector("#phone");
window.intlTelInput(input, {
utilsScript: "path/to/utils.js"
});
- (Optional) Handle the validation on form submission:
form.addEventListener('submit', function(e) {
e.preventDefault();
if (iti.isValidNumber()) {
// Process the valid number
} else {
// Show error message
}
});
Competitor Comparisons
Cross-browser QRCode generator for javascript
Pros of qrcodejs
- Lightweight and focused solely on QR code generation
- No external dependencies, making it easy to integrate
- Supports various output formats (canvas, table, SVG)
Cons of qrcodejs
- Less actively maintained compared to intl-tel-input
- Limited functionality beyond QR code generation
- Lacks built-in styling options for customization
Code Comparison
qrcodejs:
var qrcode = new QRCode("qrcode", {
text: "https://example.com",
width: 128,
height: 128
});
intl-tel-input:
var input = document.querySelector("#phone");
window.intlTelInput(input, {
utilsScript: "path/to/utils.js"
});
While qrcodejs focuses on generating QR codes with minimal setup, intl-tel-input provides a more comprehensive solution for handling international phone numbers with additional features and customization options. The code examples demonstrate the simplicity of qrcodejs for QR code generation compared to the more complex setup required for intl-tel-input's phone number input functionality.
Google's common Java, C++ and JavaScript library for parsing, formatting, and validating international phone numbers.
Pros of libphonenumber
- More comprehensive phone number parsing and validation
- Supports a wider range of countries and formats
- Regularly updated with new phone number patterns and metadata
Cons of libphonenumber
- Larger library size, which may impact load times
- More complex implementation, requiring additional setup
- Less focus on UI components, primarily a backend library
Code Comparison
intl-tel-input:
$("#phone").intlTelInput({
utilsScript: "path/to/utils.js",
preferredCountries: ["us", "gb"]
});
libphonenumber:
const phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();
const number = phoneUtil.parse('+1 650-253-0000', 'US');
console.log(phoneUtil.isValidNumber(number));
Summary
intl-tel-input is a lightweight, user-friendly library focused on providing an interactive phone input UI component. It's easier to implement and offers a visually appealing interface out of the box.
libphonenumber, on the other hand, is a more robust and comprehensive solution for phone number parsing, validation, and formatting. It's better suited for complex backend operations and supports a wider range of countries and formats.
Choose intl-tel-input for simple, frontend-focused projects, and libphonenumber for more extensive, backend-heavy applications requiring advanced phone number handling.
PHP version of Google's phone number handling library
Pros of libphonenumber-for-php
- More comprehensive phone number parsing and validation capabilities
- Based on Google's libphonenumber library, ensuring high accuracy and regular updates
- Supports a wider range of phone number-related operations (e.g., formatting, carrier lookup)
Cons of libphonenumber-for-php
- Requires server-side processing, which may increase server load
- Lacks built-in UI components for phone number input
- More complex implementation compared to client-side solutions
Code Comparison
libphonenumber-for-php:
$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
$phoneNumber = $phoneUtil->parse($number, $countryCode);
$isValid = $phoneUtil->isValidNumber($phoneNumber);
intl-tel-input:
var input = document.querySelector("#phone");
var iti = window.intlTelInput(input);
var isValid = iti.isValidNumber();
Key Differences
- libphonenumber-for-php is a server-side PHP library, while intl-tel-input is a client-side JavaScript plugin
- intl-tel-input provides a user-friendly interface for phone number input, including country selection
- libphonenumber-for-php offers more advanced phone number manipulation and analysis features
- intl-tel-input is easier to implement for basic phone number validation in web forms
- libphonenumber-for-php is better suited for applications requiring extensive phone number processing and analysis
Both libraries have their strengths and are suitable for different use cases, depending on the specific requirements of the project.
Google's common JavaScript library
Pros of closure-library
- Comprehensive JavaScript library with a wide range of utilities and components
- Robust and well-tested, used in large-scale Google applications
- Supports modular development and code optimization
Cons of closure-library
- Steeper learning curve due to its size and complexity
- May be overkill for smaller projects or specific use cases
- Less focused on internationalization features compared to intl-tel-input
Code Comparison
intl-tel-input:
var input = document.querySelector("#phone");
window.intlTelInput(input, {
utilsScript: "path/to/utils.js"
});
closure-library:
goog.require('goog.dom');
goog.require('goog.ui.InputDatePicker');
var datePickerInput = new goog.ui.InputDatePicker();
datePickerInput.render(goog.dom.getElement('datepicker'));
Summary
While closure-library offers a comprehensive set of tools for large-scale JavaScript applications, intl-tel-input is more focused on providing a specific solution for international telephone input fields. closure-library's breadth of features comes at the cost of increased complexity, while intl-tel-input offers a simpler, more targeted approach for its specific use case.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
International Telephone Input
NEWS: we now have our own Vue component!
NEWS: we now have our own React component! Play with it on Storybook.
ð£ï¸ NEWS: we now provide translations in over 30 languages! See them in action.
International Telephone Input is a JavaScript plugin for entering and validating international telephone numbers. It takes a regular input field, adds a searchable country dropdown, auto-detects the user's country, displays a relevant placeholder number, formats the number as you type, and provides comprehensive validation methods. Now includes React and Vue components.
If you find the plugin helpful, please consider supporting the project.
Sponsored by
Use Twilio's API to build phone verification, SMS 2FA, appointment reminders, marketing notifications and so much more. We can't wait to see what you build.Table of Contents
- React and Vue Components
- Demo and Examples
- Mobile
- Features
- Browser Compatibility
- Getting Started
- Recommended Usage
- Initialisation Options
- Instance Methods
- Static Methods
- Events
- Theming / Dark Mode
- Utilities Script
- Loading The Utilities Script
- Troubleshooting
- Contributing
- Attributions
React and Vue Components
We now provide both React and Vue components alongside the regular JavaScript plugin. This readme is for the JavaScript plugin. View the React Component readme or the Vue Component readme.
Demo and Examples
You can view a live demo and see some examples of how to use the various options. Alternatively, try it for yourself by downloading the project and opening demo.html in a browser.
Mobile
By default, on mobile devices we show a fullscreen popup instead of the inline dropdown, to make better use of the limited screen space. This is similar to how a native <select>
element works. You can control this behaviour with the useFullscreenPopup
option. The popup can be closed by either selecting a country from the list or by tapping on the grey area at the sides. See example (using the React component).
Features
- Automatically select the user's current country using an IP lookup
- Automatically set the input placeholder to an example number for the selected country
- Navigate the country dropdown by typing a country's name, or using the up/down keys
- Automatically format the number as the user types
- Optionally only allow numeric characters and cap the number at the maximum valid length
- The user types their national number and the plugin gives you the full standardised international number
- Number validation, including specific error types
- High-resolution flag images
- Accessibility provided via ARIA tags
- Typescript type definitions included
- Easily customise styles by overriding CSS variables
- React and Vue components included
- Translations for country names (etc) provided for over 30 different languages
- Lots of initialisation options for customisation, as well as instance methods/events for interaction
Browser Compatibility
Chrome | Firefox | Safari | Edge |
---|---|---|---|
â | â | â | â |
Note: We have now dropped support for all versions of Internet Explorer because it is no longer supported by any version of Windows.
Getting Started (Using a CDN)
- Add the CSS
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/intl-tel-input@24.4.0/build/css/intlTelInput.css">
- Add the plugin script and initialise it on your input element
<script src="https://cdn.jsdelivr.net/npm/intl-tel-input@24.4.0/build/js/intlTelInput.min.js"></script>
<script>
const input = document.querySelector("#phone");
window.intlTelInput(input, {
utilsScript: "https://cdn.jsdelivr.net/npm/intl-tel-input@24.4.0/build/js/utils.js",
});
</script>
Getting Started (Using a bundler e.g. Webpack)
-
Install with npm:
npm install intl-tel-input --save
or yarn:yarn add intl-tel-input
-
Import the CSS:
import 'intl-tel-input/build/css/intlTelInput.css';
-
Set the path to flags.webp and globe.webp in your CSS, by overriding the CSS variables
.iti {
--iti-path-flags-1x: url('path/to/flags.webp');
--iti-path-flags-2x: url('path/to/flags@2x.webp');
--iti-path-globe-1x: url('path/to/globe.webp');
--iti-path-globe-2x: url('path/to/globe@2x.webp');
}
- Import the JS and initialise the plugin on your input element
import intlTelInput from 'intl-tel-input';
const input = document.querySelector("#phone");
intlTelInput(input, {
utilsScript: "path/to/utils.js"
});
Getting Started (Not using a bundler)
-
Download the latest release, or better yet install it with npm
-
Add the stylesheet
<link rel="stylesheet" href="path/to/intlTelInput.css">
- Set the path to flags.webp and globe.webp in your CSS, by overriding the CSS variables
.iti {
--iti-path-flags-1x: url('path/to/flags.webp');
--iti-path-flags-2x: url('path/to/flags@2x.webp');
--iti-path-globe-1x: url('path/to/globe.webp');
--iti-path-globe-2x: url('path/to/globe@2x.webp');
}
- Add the plugin script and initialise it on your input element
<script src="path/to/intlTelInput.js"></script>
<script>
const input = document.querySelector("#phone");
window.intlTelInput(input, {
utilsScript: "path/to/utils.js"
});
</script>
Recommended Usage
We highly recommend you load the included utils.js, which enables formatting and validation etc. Then the plugin is built to always deal with numbers in the full international format (e.g. "+17024181234") and convert them accordingly - even when nationalMode
or separateDialCode
is enabled. We recommend you get, store, and set numbers exclusively in this format for simplicity - then you don't have to deal with handling the country code separately, as full international numbers include the country code information.
You can always get the full international number (including country code) using getNumber
, then you only have to store that one string in your database (you don't have to store the country separately), and then the next time you initialise the plugin with that number in the input, it will automatically set the country and format it according to the options you specify (e.g. when using nationalMode
it will automatically display the number in national format, removing the international dial code).
If you know the user's country, you can set it with initialCountry
(e.g. "us"
for the United States), and if you don't, we recommend setting initialCountry
to "auto"
(along with the geoIpLookup
option) to determine the user's country based on their IP address - see example.
If you know the user's language, you can use the included translations to localise the country names (etc) - see example.
Initialisation Options
When you initialise the plugin, the first argument is the input element, and the second is an object containing any initialisation options you want, which are detailed below. Note: any options that take country codes should be ISO 3166-1 alpha-2 codes.
allowDropdown
Type: Boolean
Default: true
Whether or not to allow the dropdown. If disabled, there is no dropdown arrow, and the selected country is not clickable. Also, if showFlags is enabled we display the selected flag on the right instead because it is just a marker of state. Note that if separateDialCode
is enabled, allowDropdown
is forced to true
as the dropdown is required when the user types "+" in this case. Play with this option on Storybook (using the React component).
autoPlaceholder
Type: String
Default: "polite"
Set the input's placeholder to an example number for the selected country, and update it if the country changes. You can specify the number type using the placeholderNumberType
option. By default, it is set to "polite"
, which means it will only set the placeholder if the input doesn't already have one. You can also set it to "aggressive"
, which will replace any existing placeholder, or "off"
. Requires the utils script to be loaded.
containerClass
Type: String
Default: ""
Additional classes to add to the (injected) wrapper <div>
.
countryOrder
Type: Array
Default: null
Specify the ordering for the country list with an array of iso2 country codes. Any omitted countries will appear after those specified e.g. setting countryOrder
to ["jp", "kr"]
will result in the list: Japan, South Korea, Afghanistan, Albania, Algeria etc...
countrySearch
Type: Boolean
Default: true
Add a search input to the top of the dropdown, so users can filter the displayed countries.
customPlaceholder
Type: Function
Default: null
Change the placeholder generated by autoPlaceholder. Must return a string.
intlTelInput(input, {
customPlaceholder: function(selectedCountryPlaceholder, selectedCountryData) {
return "e.g. " + selectedCountryPlaceholder;
},
});
dropdownContainer
Type: Node
Default: null
Expects a node e.g. document.body
. Instead of putting the country dropdown markup next to the input, append it to the specified node, and it will then be positioned next to the input using JavaScript (using position: fixed
). This is useful when the input is inside a container with overflow: hidden
. Note that the positioning is broken by scrolling, so the dropdown will automatically close on the window
scroll event.
excludeCountries
Type: Array
Default: []
In the dropdown, display all countries except the ones you specify here. Play with this option on Storybook (using the React component).
fixDropdownWidth
Type: Boolean
Default: true
Fix the dropdown width to the input width (rather than being as wide as the longest country name). Play with this option on Storybook (using the React component).
formatAsYouType
Type: Boolean
Default: true
Automatically format the number as the user types. This feature will be disabled if the user types their own formatting characters. Requires the utils script to be loaded.
formatOnDisplay
Type: Boolean
Default: true
Format the input value (according to the nationalMode
option) during initialisation, and on setNumber
. Requires the utils script to be loaded.
geoIpLookup
Type: Function
Default: null
When setting initialCountry
to "auto"
, you must use this option to specify a custom function that calls an IP lookup service to get the user's location and then invokes the success
callback with the relevant country code. Also note that when instantiating the plugin, a Promise object is returned under the promise
instance property, so you can do something like iti.promise.then(...)
to know when initialisation requests like this have completed.
Here is an example using the ipapi service:
intlTelInput(input, {
initialCountry: "auto",
geoIpLookup: function(success, failure) {
fetch("https://ipapi.co/json")
.then(function(res) { return res.json(); })
.then(function(data) { success(data.country_code); })
.catch(function() { failure(); });
}
});
Note that the failure
callback must be called in the event of an error, hence the use of catch()
in this example. Tip: store the result in a cookie to avoid repeat lookups!
hiddenInput
Type: Function
Default: null
Allows the creation of hidden input fields within a form to store the full international telephone number and the selected country code. It accepts a function that receives the name of the main telephone input as an argument. This function should return an object with phone
and (optionally) country
properties to specify the names of the hidden inputs for the phone number and country code, respectively. This is useful for non-Ajax form submissions to ensure the full international number and country code are captured, especially when nationalMode
is enabled.
*Note: This feature requires the input to be inside a <form>
element, as it listens for the submit
event on the closest form element. Also note that since this uses getNumber
internally, firstly it requires the utils script to be loaded, and secondly it expects a valid number and so will only work correctly if you have used isValidNumber
to validate the number before allowing the form submit to go through.
intlTelInput(input, {
hiddenInput: function(telInputName) {
return {
phone: "phone_full",
country: "country_code"
};
}
});
This will generate the following (hidden) elements, which will be automatically populated on submit:
<input type="hidden" name="phone_full">
<input type="hidden" name="country_code">
i18n
Type: Object
Default: {}
Allow localisation/customisation of the 200+ country names, as well as other user interface text (e.g. the placeholder text for the country search input). The easiest way to do this is to simply import one of the provided translation modules and set i18n
to that value (see option 1 below). You can also override one or more individual keys this way (see option 1 below). Alternatively, you can provide your own custom translations (see option 2 below). If providing your own, you will need to specify all the country names (which can be copied from the country-list project e.g. here are the country names in French), as well as a few UI strings (listed below). See example.
If we don't currently support a language you need, it's easy to contribute this yourself - you only need to provide a handful of UI translation strings, as we automatically pull in the country names from the country-list project.
Option 1: import one of the provided translation modules
import { fr } from "intl-tel-input/i18n";
intlTelInput(input, {
i18n: fr,
});
// or to override one or more keys, you could do something like this
intlTelInput(input, {
i18n: {
...fr,
searchPlaceholder: "Recherche de pays",
},
});
Option 2: define your own custom translations
intlTelInput(input, {
i18n: {
// Country names - see the full list in src/js/intl-tel-input/i18n/en/countries.ts
af: "Afghanistan",
al: "Albania",
dz: "Algeria",
as: "American Samoa",
ad: "Andorra",
...
// Aria label for the selected country element
selectedCountryAriaLabel: "Selected country",
// Screen reader text for when no country is selected
noCountrySelected: "No country selected",
// Aria label for the country list element
countryListAriaLabel: "List of countries",
// Placeholder for the search input in the dropdown
searchPlaceholder: "Search",
// Screen reader text for when the search produces no results
zeroSearchResults: "No results found",
// Screen reader text for when the search produces 1 result
oneSearchResult: "1 result found",
// Screen reader text for when the search produces multiple results
multipleSearchResults: "${count} results found",
}
});
initialCountry
Type: String
Default: ""
Set the initial country selection by specifying its country code e.g. "us"
for the United States. (Be careful not to do this unless you are sure of the user's country, as it can lead to tricky issues if set incorrectly and the user auto-fills their national number and submits the form without checking - in certain cases, this can pass validation and you can end up storing a number with the wrong dial code). You can also set initialCountry
to "auto"
, which will look up the user's country based on their IP address (requires the geoIpLookup
option - see example). Note that however you use initialCountry
, it will not update the country selection if the input already contains a number with an international dial code.
nationalMode
Type: Boolean
Default: true
Format numbers in the national format, rather than the international format. This applies to placeholder numbers, and when displaying users' existing numbers. Note that it's fine for users to type their numbers in national format - as long as they have selected the right country, you can use getNumber
to extract a full international number - see example. It is recommended to leave this option enabled, to encourage users to enter their numbers in national format as this is usually more familiar to them and so it creates a better user experience.
onlyCountries
Type: Array
Default: []
In the dropdown, display only the countries you specify - see example.
placeholderNumberType
Type: String
Default: "MOBILE"
Specify one of the keys from the enum intlTelInput.utils.numberType
(e.g. "FIXED_LINE"
) to set the number type to use for the placeholder. Play with this option on Storybook (using the React component).
showFlags
Type: Boolean
Default: true
Set this to false to hide the flags e.g. for political reasons. Instead, it will show a generic globe icon. Play with this option on Storybook (using the React component).
separateDialCode
Type: Boolean
Default: false
Display the selected country's international dial code next to the input, so it looks like it's part of the typed number. Since the user cannot edit the displayed dial code, they may try to type a new one - in this case, to avoid having two dial codes next to each other, we automatically open the country dropdown and put the new dial code in the search input instead. So if they type +54, then Argentina will be highlighted in the dropdown and they can simply press Enter to select it, updating the displayed dial code (this feature requires allowDropdown
and countrySearch
to be enabled). Play with this option on Storybook (using the React component).
strictMode
Type: Boolean
Default: false
As the user types in the input, ignore any irrelevant characters. The user can only enter numeric characters and an optional plus at the beginning. Cap the length at the maximum valid number length (this respects validationNumberType
). Requires the utils script to be loaded. See example.
useFullscreenPopup
Type: Boolean
Default: true on mobile devices, false otherwise
Control when the country list appears as a fullscreen popup vs an inline dropdown. By default, it will appear as a fullscreen popup on mobile devices (based on user-agent and screen width), to make better use of the limited space (similar to how a native <select>
works), and as an inline dropdown on larger devices/screens. Play with this option on Storybook (using the React component).
utilsScript
Type: String
Default: ""
Example: "/build/js/utils.js"
This is one way to (lazy) load the included utils.js (to enable formatting/validation etc) - see Loading The Utilities Script for more options. You will need to host the utils.js file, and then set the utilsScript
option to that URL, or alternatively just point it to a CDN hosted version e.g. "https://cdn.jsdelivr.net/npm/intl-tel-input@24.4.0/build/js/utils.js"
. The script is loaded via a dynamic import statement, which means the URL cannot be relative - it must be absolute. The script is only fetched when you initialise the plugin, and additionally, only when the page has finished loading (on the window load event) to prevent blocking (the script is ~260KB). When instantiating the plugin, a Promise object is returned under the promise
instance property, so you can do something like iti.promise.then(callback)
to know when initialisation requests like this have finished. See Utilities Script for more information.
validationNumberType
Type: String
Default: "MOBILE"
Specify one of the keys from the enum intlTelInput.utils.numberType
(e.g. "FIXED_LINE"
) to set the number type to enforce during validation with isValidNumber
, as well as the number length to enforce with strictMode
. Set it to null
to not enforce any particular type.
Instance Methods
In these examples, iti
refers to the plugin instance which gets returned when you initialise the plugin e.g.
const iti = intlTelInput(input);
destroy
Remove the plugin from the input, and unbind any event listeners.
iti.destroy();
getExtension
Get the extension from the current number. Requires the utils script to be loaded.
const extension = iti.getExtension();
Returns a string e.g. if the input value was "(702) 555-5555 ext. 1234"
, this would return "1234"
getNumber
Get the current number in the given format (defaults to E.164 standard). The different formats are available in the enum intlTelInput.utils.numberFormat
- which you can see here. Requires the utils script to be loaded. Note that even if nationalMode
is enabled, this can still return a full international number. Also note that this method expects a valid number, and so should only be used after validation.
const number = iti.getNumber();
// or
const number = iti.getNumber(intlTelInput.utils.numberFormat.E164);
Returns a string e.g. "+17024181234"
getNumberType
Get the type (fixed-line/mobile/toll-free etc) of the current number. Requires the utils script to be loaded.
const numberType = iti.getNumberType();
Returns an integer, which you can match against the various options in the enum intlTelInput.utils.numberType
e.g.
if (numberType === intlTelInput.utils.numberType.MOBILE) {
// is a mobile number
}
Note that in the US there's no way to differentiate between fixed-line and mobile numbers, so instead it will return FIXED_LINE_OR_MOBILE
.
getSelectedCountryData
Get the country data for the currently selected country.
const countryData = iti.getSelectedCountryData();
Returns something like this:
{
name: "Afghanistan",
iso2: "af",
dialCode: "93"
}
getValidationError
Get more information about a validation error. Requires the utils script to be loaded.
const error = iti.getValidationError();
Returns an integer, which you can match against the various options in the enum intlTelInput.utils.validationError
e.g.
if (error === intlTelInput.utils.validationError.TOO_SHORT) {
// the number is too short
}
isValidNumber
Check if the current number is valid based on its length - see example, which should be sufficient for most use cases. See isValidNumberPrecise
for more precise validation, but the advantage of isValidNumber
is that it is much more future-proof as while countries around the world regularly update their number rules, they very rarely change their number lengths. If this method returns false
, you can use getValidationError
to get more information. Respects the validationNumberType
option (which is set to "MOBILE" by default). Requires the utils script to be loaded.
const isValid = iti.isValidNumber();
Returns: true
/false
isValidNumberPrecise
Check if the current number is valid using precise matching rules for each country/area code etc - see example. Note that these rules change each month for various countries around the world, so you need to be careful to keep the plugin up-to-date else you will start rejecting valid numbers. For a simpler and more future-proof form of validation, see isValidNumber
above. If validation fails, you can use getValidationError
to get more information. Requires the utils script to be loaded.
const isValid = iti.isValidNumberPrecise();
Returns: true
/false
setCountry
Change the selected country. It should be rare, if ever, that you need to do this, as the selected country gets updated automatically when calling setNumber
and passing a number including an international dial code, which is the recommended usage. Note you can omit the country code argument to set the country to the default empty (globe) state.
iti.setCountry("gb");
setNumber
Insert a number, and update the selected country accordingly. Note that if formatOnDisplay
is enabled, this will attempt to format the number to either national or international format according to the nationalMode
option.
iti.setNumber("+447733123456");
setPlaceholderNumberType
Change the placeholderNumberType option.
iti.setPlaceholderNumberType("FIXED_LINE");
setDisabled
Updates the disabled attribute of both the telephone input and the selected country button. Accepts a boolean value. Note: we recommend using this instead of updating the disabled attribute of the input directly.
iti.setDisabled(true);
Static Methods
getCountryData
Retrieve the plugin's country data - either to re-use elsewhere e.g. to generate your own country dropdown - see example, or alternatively, you could use it to modify the country data. Note that any modifications must be done before initialising the plugin.
const countryData = intlTelInput.getCountryData();
Returns an array of country objects:
[{
name: "Afghanistan",
iso2: "af",
dialCode: "93"
}, ...]
getInstance
After initialising the plugin, you can always access the instance again using this method, by just passing in the relevant input element.
const input = document.querySelector('#phone');
const iti = intlTelInput.getInstance(input);
iti.isValidNumber(); // etc
loadUtils
An alternative to the utilsScript
option, this method lets you manually load the utils.js script on demand, to enable formatting/validation etc. See Loading The Utilities Script for more information. This method should only be called once per page. A Promise object is returned so you can use loadUtils().then(callback)
to know when it's finished.
intlTelInput.loadUtils("/build/js/utils.js");
Events
You can listen for the following events triggered on the input element.
countrychange
This is triggered when the selected country is updated e.g. if the user selects a country from the dropdown, or they type a different dial code into the input, or you call setCountry
etc.
input.addEventListener("countrychange", function() {
// do something with iti.getSelectedCountryData()
});
See an example here: Country sync
open:countrydropdown
This is triggered when the user opens the dropdown.
close:countrydropdown
This is triggered when the user closes the dropdown.
Theming / Dark Mode
There are lots of CSS variables available for theming. See intlTelInput.scss for the full list.
As for the empty state (globe icon), the default version is dark grey, and we also provide a "light" version, that should work better with a dark theme. Alternatively, it's easy to re-generate the globe icon in whatever colour you need for your theme. We recommend you download it in the highest resolution possible, and then scale the image down to the required sizes (20px wide for the default version and 40px wide for the @2x version).
Dark mode example (with screenshot below):
@media (prefers-color-scheme: dark) {
.iti {
--iti-border-color: #5b5b5b;
--iti-dialcode-color: #999999;
--iti-dropdown-bg: #0d1117;
--iti-arrow-color: #aaaaaa;
--iti-hover-color: #30363d;
--iti-path-globe-1x: url("path/to/globe_light.webp");
--iti-path-globe-2x: url("path/to/globe_light@2x.webp");
}
}
NOTE: this assumes you already have your own dark mode styling in place for general body/input styling e.g. something like this:
@media (prefers-color-scheme: dark) {
body, input {
color: white;
background-color: #0d1117;
}
input {
border-color: #5b5b5b;
}
input::placeholder {
color: #8d96a0;
}
}
Example:
Utilities Script
The utilities script (build/js/utils.js) is a custom build of Google's libphonenumber which enables the following features:
- Formatting upon initialisation, as well as with
getNumber
andsetNumber
- Validation with
isValidNumber
,getNumberType
andgetValidationError
methods - Placeholder set to an example number for the selected country - even specify the type of number (e.g. mobile) using the
placeholderNumberType
option - Extract the standardised (E.164) international number with
getNumber
even when using thenationalMode
option
International number formatting/validation is hard (it varies by country/district, and we currently support ~230 countries). The only comprehensive solution we have found is libphonenumber, from which we have precompiled the relevant parts into a single JavaScript file, included in the build directory. Unfortunately, even after modification, it is still ~260KB. See the section below on the best way to load it.
To recompile the utils script yourself (e.g. to update the version of libphonenumber it is built from), see the contributing guide.
Loading The Utilities Script
The utils script provides lots of great functionality (see above section), but comes at the cost of increased filesize (~260KB). There are two main ways to load the utils script, depending on whether you're concerned about filesize or not.
Option 1: intlTelInputWithUtils
If you're not concerned about filesize (e.g. you're lazy loading this script), the easiest thing to do is to just use the full bundle /build/js/intlTelInputWithUtils.js, which comes with the utils script included. This script can be used exactly like the main intlTelInput.js - so it can either be loaded directly onto the page (which defines window.intlTelInput
like usual), or it can be imported like so: import intlTelInput from "intl-tel-input/intlTelInputWithUtils"
.
Option 2: utilsScript
If you are concerned about filesize, you can lazy load the utils script when the plugin initialises, using the utilsScript
initialisation option. You will need to host the utils.js file, and then set the utilsScript
option to that URL, or just point it to a CDN hosted version e.g. "https://cdn.jsdelivr.net/npm/intl-tel-input@24.4.0/build/js/utils.js"
. If you want more control over when this file is lazy loaded, you can manually invoke the loadUtils
static method, instead of using utilsScript
.
Troubleshooting
Full-width input
If you want your input to be full-width, you need to set the container to be the same i.e.
.iti { width: 100%; }
dropdownContainer: dropdown not closing on scroll
If you have a scrolling container other than window
which is causing problems by not closing the dropdown on scroll, simply listen for the scroll event on that element, and trigger a scroll event on window
, which in turn will close the dropdown e.g.
scrollingElement.addEventListener("scroll", function() {
const e = document.createEvent('Event');
e.initEvent("scroll", true, true);
window.dispatchEvent(e);
});
Input margin
For the sake of alignment, the default CSS forces the input's vertical margin to 0px
. If you want vertical margin, you should add it to the container (with class iti
).
Displaying error messages
If your error handling code inserts an error message before the <input>
it will break the layout. Instead, you must insert it before the container (with class iti
).
Dropdown position
The dropdown should automatically appear above/below the input depending on the available space. For this to work properly, you must only initialise the plugin after the <input>
has been added to the DOM.
Placeholders
To get the automatic country-specific placeholders, simply omit the placeholder attribute on the <input>
, or set autoPlaceholder
to "aggressive"
to override any existing placeholder,
Bootstrap input groups
A couple of CSS fixes are required to get the plugin to play nice with Bootstrap input groups. You can see a Codepen here.
Note: there is currently a bug in Mobile Safari which causes a crash when you click the dropdown arrow (a CSS triangle) inside an input group. The simplest workaround is to remove the CSS triangle with this line:
.iti__arrow { border: none; }
Contributing
See the contributing guide for instructions on setting up the project and making changes, and also on how to update to a new version of libphonenumber, how to update the flag images, or how to add a new translation.
Attributions
- Flag images from flag-icons
- Original country data from mledoze's World countries in JSON, CSV and XML
- Formatting/validation/example number code from libphonenumber
- Feature contributions are listed in the wiki: Contributions
Links
- List of integrations with intl-tel-input
Testing powered by BrowserStack Open-Source Program
Top Related Projects
Cross-browser QRCode generator for javascript
Google's common Java, C++ and JavaScript library for parsing, formatting, and validating international phone numbers.
PHP version of Google's phone number handling library
Google's common JavaScript library
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot