Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
intl-tel-input
Advanced tools
The intl-tel-input npm package is a JavaScript plugin for entering and validating international telephone numbers. It adds a flag dropdown to any input, which lists all the countries and their international dial codes. It also provides validation and formatting functionalities.
Initialize the plugin
This code initializes the intl-tel-input plugin on an input field with the id 'phone'. The 'utilsScript' option is used to specify the path to the utils.js file, which is necessary for some of the plugin's advanced functionalities.
const input = document.querySelector('#phone');
const iti = window.intlTelInput(input, {
utilsScript: 'path/to/utils.js'
});
Get the selected country data
This code retrieves the data of the currently selected country, including the country name, dial code, and ISO2 code.
const countryData = iti.getSelectedCountryData();
console.log(countryData);
Set the country
This code sets the country to the United States by passing the ISO2 code 'us'.
iti.setCountry('us');
Validate the phone number
This code checks if the entered phone number is valid according to the selected country's format.
const isValid = iti.isValidNumber();
console.log(isValid);
Get the full phone number
This code retrieves the full phone number in international format.
const fullNumber = iti.getNumber();
console.log(fullNumber);
react-phone-input-2 is a React component for entering and validating international telephone numbers. It provides similar functionalities to intl-tel-input, such as country selection and phone number validation, but is specifically designed for use with React applications.
react-intl-tel-input is another React component that wraps the intl-tel-input plugin. It offers the same features as intl-tel-input but is tailored for React, making it easier to integrate into React projects.
vue-tel-input is a Vue.js component for international telephone input. It provides similar functionalities to intl-tel-input, including country selection and phone number validation, but is designed for use with Vue.js applications.
A jQuery plugin for entering and validating international telephone numbers. It adds a flag dropdown to any input, which lists all the countries and their international dial codes next to their flags.
You can view a live demo and some examples of how to use the various options here: http://jackocnr.com/intl-tel-input.html, or try it for yourself using the included demo.html.
Chrome | Firefox | Safari | IE | Android (Chrome) | Mobile Safari | IE Mobile | |
---|---|---|---|---|---|---|---|
Core | ✓ | ✓ | ✓ | 8 | ✓ | ✓ | ✓ |
autoFormat | ✓ | ✓ | ✓ | 9 | ✗ | ✓ | ✗ |
bower install intl-tel-input
<link rel="stylesheet" href="build/css/intlTelInput.css">
<input type="tel" id="mobile-number">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="build/js/intlTelInput.min.js"></script>
<script>
$("#mobile-number").intlTelInput();
</script>
Note: any options that take country codes should be lower case ISO 3166-1 alpha-2 codes
autoFormat
Type: Boolean
Default: true
Format the number on each keypress according to the country-specific formatting rules. This will also prevent the user from entering invalid characters. Requires the utilsScript option for the formatting logic.
autoHideDialCode
Type: Boolean
Default: true
If there is just a dial code in the input: remove it on blur, and re-add it on focus. This is to prevent just a dial code getting submitted with the form.
defaultCountry
Type: String
Default: ""
Set the default country by it's country code. You can also set it to "auto", which will lookup the user's country based on their IP address. Otherwise it will just be the first country in the list.
nationalMode
Type: Boolean
Default: false
Don't insert the international dial code when the user selects a country from the dropdown. Useful if you want to accept numbers in national format, and then you can use getSelectedCountryData
to get the selected country's dial code.
onlyCountries
Type: Array
Default: undefined
Display only the countries you specify.
preferredCountries
Type: Array
Default: ["us", "gb"]
Specify the countries to appear at the top of the list.
responsiveDropdown
Type: Boolean
Default: false
Set the dropdown's width to be the same as the input. This is automatically enabled for small screens.
utilsScript
Type: String
Default: ""
Example: "lib/libphonenumber/build/utils.js"
Enable formatting/validation/example numbers (for placeholders) by specifying the URL to the included utils.js script (~200KB), which is fetched only when the page has finished loading (on window.load) to prevent blocking. See Utilities Script for more information. Note that if you're lazy loading the plugin script (after the window.load event) this will not work and you will need to use the loadUtils method instead.
destroy
Remove the plugin from the input, and unbind any event listeners.
$("#mobile-number").intlTelInput("destroy");
getCleanNumber
Get the current number formatted to the E.164 standard. Requires the utilsScript option. Note that even if nationalMode is enabled, this will still return an international number, as specified by the E.164 standard.
var cleanNumber = $("#mobile-number").intlTelInput("getCleanNumber");
Returns a string e.g. "+17024181234"
getNumberType
Get the type (fixed-line/mobile/toll-free etc) of the current number. Requires the utilsScript option.
var numberType = $("#mobile-number").intlTelInput("getNumberType");
Returns an integer, which you can match against the various options in the global enum intlTelInputUtils.numberType
e.g.
if (numberType == intlTelInputUtils.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 flag.
var countryData = $("#mobile-number").intlTelInput("getSelectedCountryData");
Returns something like this:
{
name: "Afghanistan (افغانستان)",
iso2: "af",
dialCode: "93"
}
getValidationError
Get more information about a validation error.
var error = $("#mobile-number").intlTelInput("getValidationError");
Returns an integer, which you can match against the various options in the global enum intlTelInputUtils.validationError
e.g.
if (error == intlTelInputUtils.validationError.TOO_SHORT) {
// the number is too short
}
isValidNumber
Validate the current number using Google's libphonenumber (requires the utilsScript option). Expects an internationally formatted number (unless nationalMode is enabled).
var isValid = $("#mobile-number").intlTelInput("isValidNumber");
Returns: true/false
loadUtils
Load the utils script - either pass the path as an argument, or it will default to the value of the utilsScript option. Use this if you're lazy loading the plugin script (in which case the utilsScript option will not work as it relies on the window.load event).
$("#mobile-number").intlTelInput("loadUtils", "lib/libphonenumber/build/utils.js");
selectCountry
Change the country selection (e.g. when the user is entering their address).
$("#mobile-number").intlTelInput("selectCountry", "gb");
setNumber
Insert a number, and update the selected flag accordingly.
$("#mobile-number").intlTelInput("setNumber", "+44 7733 123 456");
getCountryData
Get all of the plugin's country data.
var countryData = $.fn.intlTelInput.getCountryData();
Returns an array of country objects:
[{
name: "Afghanistan (افغانستان)",
iso2: "af",
dialCode: "93"
}, ...]
setCountryData
Set all of the plugin's country data.
$.fn.intlTelInput.setCountryData(countryData);
International number formatting/validation is hard (it varies by country/district). The only comprehensive solution I have found is Google's libphonenumber, which I have precompiled into a single JavaScript file and included in the lib directory. Unfortunately even after minification it is still ~200KB, so I have included it as an optional extra. If you specify the utilsScript option then it will fetch the script only when the page has finished loading (to prevent blocking), and allows you to use the public isValidNumber
function, autoFormat mode and will automatically update your input's placeholder to an example number for the selected country.
Image path
Depending on your project setup, you may need to override the path to flags.png in your CSS.
.intl-tel-input .flag {background-image: url("path/to/flags.png");}
Full width input
If you want your input to be full-width, you need to set the container to be the same i.e.
.intl-tel-input {width: 100%;}
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 intl-tel-input
).
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 intl-tel-input
).
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
In order to get the automatic country-specific placeholders, simply omit the placeholder attribute on the <input>
.
I'm very open to contributions, big and small! For instructions on contributing to a project on Github, see this guide: Fork A Repo.
I use Grunt to build the project, which relies on npm. In the project directory, run npm install
to install Grunt (and other dependencies), then make your changes in the src
directory and run grunt build
to build the project.
FAQs
A JavaScript plugin for entering and validating international telephone numbers
The npm package intl-tel-input receives a total of 343,247 weekly downloads. As such, intl-tel-input popularity was classified as popular.
We found that intl-tel-input demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.