Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

intl-tel-input-boegebjerg

Boegebjerg20MIT12.1.8

A jQuery plugin for entering international telephone numbers

international, i18n, country, dial, code, telephone, mobile, input, flag

readme

International Telephone Input Build Status

A jQuery 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.

If you like it, please consider making a donation, which you can do from the demo page.

Table of Contents

Demo and Examples

You can view a live demo and some examples of how to use the various options here: http://intl-tel-input.com, or try it for yourself using the included demo.html.

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 up/down keys
  • Handle phone number extensions
  • The user types their national number and the plugin gives you the full standardized international number
  • Full validation, including specific error types
  • Retina flag icons
  • Lots of initialisation options for customisation, as well as public methods for interaction

Browser Compatibility

Chrome FF Safari IE Chrome Android Mobile Safari IE Mob
11

Note: In v12.0.0 we dropped support for IE9 and IE10, because they are no longer supported by any version of Windows - see https://www.xfive.co/blog/stop-supporting-ie10-ie9-ie8/

Getting Started

  1. Download the latest release, or better yet install it with npm

  2. Include the stylesheet

    <link rel="stylesheet" href="path/to/intlTelInput.css">
  3. Override the path to flags.png in your CSS

    .iti-flag {background-image: url("path/to/flags.png");}
    
    @media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min--moz-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 2 / 1), only screen and (min-device-pixel-ratio: 2), only screen and (min-resolution: 192dpi), only screen and (min-resolution: 2dppx) {
     .iti-flag {background-image: url("path/to/flags@2x.png");}
    }
  4. Add the plugin script and initialise it on your input element

    <input type="tel" id="phone">
    
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="path/to/intlTelInput.js"></script>
    <script>
     $("#phone").intlTelInput();
    </script>
  5. Recommended: initialise the plugin with the utilsScript option to enable formatting/validation, and to allow you to extract full international numbers using getNumber.

We highly recommend you load the included utils.js using the utilsScript option. 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. I 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 it will automatically set the country and format it according to the options you specify (e.g. if you enable nationalMode it will automatically remove the international dial code for you).

Options

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 flag is not clickable. Also we display the selected flag on the right instead because it is just a marker of state.

autoFormat [REMOVED]
Automatically format the number as the user types. Unfortunately this had to be removed for the reasons listed here: #346 Disable and remove autoFormat feature.

autoHideDialCode
Type: Boolean Default: true
If there is just a dial code in the input: remove it on blur or submit, and re-add it on focus. This is to prevent just a dial code getting submitted with the form. Requires nationalMode to be set to false.

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 utilsScript option.

customPlaceholder
Type: Function Default: null
Change the placeholder generated by autoPlaceholder. Must return a string.

customPlaceholder: function(selectedCountryPlaceholder, selectedCountryData) {
  return "e.g. " + selectedCountryPlaceholder;
}

dropdownContainer
Type: String Default: ""
Expects a jQuery selector e.g. "body". Instead of putting the country dropdown next to the input, append it to the element specified, and it will then be positioned absolutely next to the input using JavaScript. This is useful when the input is inside a container with overflow: hidden. Note that the absolute positioning can be broken by scrolling, so it will automatically close on the window scroll event. If you have a different scrolling element that is causing problems, simply listen for the scroll event on that element, and trigger $(window).scroll() e.g.

$("#scrollingElement").scroll(function() {
  $(window).scroll();
});

excludeCountries
Type: Array Default: undefined
Don't display the countries you specify.

formatOnDisplay
Type: Boolean Default: true
Format the input value (according to the nationalMode option) during initialisation, and on setNumber. Requires the utilsScript option.

geoIpLookup
Type: Function Default: null
When setting initialCountry to "auto", you must use this option to specify a custom function that looks up the user's location. Also note that when instantiating the plugin, we now return a deferred object, so you can use .done(callback) to know when initialisation requests like this have completed.

Here is an example using the ipinfo.io service:

geoIpLookup: function(callback) {
  $.get("https://ipinfo.io", function() {}, "jsonp").always(function(resp) {
    var countryCode = (resp && resp.country) ? resp.country : "";
    callback(countryCode);
  });
}

Note that the callback must still be called in the event of an error, hence the use of always in this example.
Tip: store the result in a cookie to avoid repeat lookups!

hiddenInput
Type: String Default: ""
Add a hidden input with the given name, and on submit, populate it with the full international number (using getNumber). This is a quick way for people using non-ajax forms to get the full international number, even when nationalMode is enabled. Note: requires the main telephone input to be inside a form element, as this feature works by listening for the submit event on the closest form element.

initialCountry
Type: String Default: ""
Set the initial country selection by specifying it's country code. You can also set it to "auto", which will lookup the user's country based on their IP address (requires the geoIpLookup option - see example). Note that the "auto" option will not update the country selection if the input already contains a number.

If you leave initialCountry blank, it will default to the first country in the list.

nationalMode
Type: Boolean Default: true
Allow users to enter national numbers (and not have to think about international dial codes). Formatting, validation and placeholders still work. Then you can use getNumber to extract a full international number - see example. This option now defaults to true, and it is recommended that you leave it that way as it provides a better experience for the user.

placeholderNumberType
Type: String Default: "MOBILE"
Specify one of the keys from the global enum intlTelInputUtils.numberType e.g. "FIXED_LINE" to set the number type to use for the placeholder.

onlyCountries
Type: Array Default: undefined
Display only the countries you specify - see example.

preferredCountries
Type: Array Default: ["us", "gb"]
Specify the countries to appear at the top of the list.

preventInvalidNumbers [REMOVED]
Prevent the user from entering invalid characters. Unfortunately this had to be removed for the reasons listed here: #79 Limit Input Characters to Formatted String Length.

separateDialCode
Type: Boolean Default: false
Display the country dial code next to the selected flag so it's not part of the typed number. Note that this will disable nationalMode because technically we are dealing with international numbers, but with the dial code separated.

utilsScript
Type: String Default: "" Example: "build/js/utils.js"
Enable formatting/validation etc. by specifying the URL of the included utils.js script (or alternatively just point it to the file on cdnjs.com). The script is fetched using Ajax when the page has finished loading (on the window.load event) to prevent blocking (the script is ~215KB). When instantiating the plugin, we return a deferred object, so you can use .done(callback) to know when initialisation requests like this have finished. See Utilities Script for more information. Note that if you're lazy loading the plugin script itself (intlTelInput.js) this will not work and you will need to use the loadUtils method instead.

Public Methods

destroy
Remove the plugin from the input, and unbind any event listeners.

$("#phone").intlTelInput("destroy");

getExtension
Get the extension from the current number. Requires the utilsScript option.

var extension = $("#phone").intlTelInput("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 intlTelInputUtils.numberFormat - which you can see here. Requires the utilsScript option. 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.

var intlNumber = $("#phone").intlTelInput("getNumber");
// or
var ntlNumber = $("#phone").intlTelInput("getNumber", intlTelInputUtils.numberFormat.E164);

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 = $("#phone").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 `FIXEDLINE_OR_MOBILE`._

getSelectedCountryData
Get the country data for the currently selected flag.

var countryData = $("#phone").intlTelInput("getSelectedCountryData");

Returns something like this:

{
  name: "Afghanistan (‫افغانستان‬‎)",
  iso2: "af",
  dialCode: "93"
}

getValidationError
Get more information about a validation error. Requires the utilsScript option.

var error = $("#phone").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 - see example. Expects an internationally formatted number (unless nationalMode is enabled). If validation fails, you can use getValidationError to get more information. Requires the utilsScript option. Also see getNumberType if you want to make sure the user enters a certain type of number e.g. a mobile number.

var isValid = $("#phone").intlTelInput("isValidNumber");

Returns: true/false

setCountry
Change the country selection (e.g. when the user is entering their address).

$("#phone").intlTelInput("setCountry", "gb");

setNumber
Insert a number, and update the selected flag accordingly. Note that if formatOnDisplay is enabled, this will attempt to format the number according to the nationalMode option.

$("#phone").intlTelInput("setNumber", "+447733123456");

setPlaceholderNumberType
Change the placeholderNumberType option.

$("#phone").intlTelInput("setPlaceholderNumberType", "FIXED_LINE");

Static Methods

getCountryData
Get all of the plugin's country data - either to re-use elsewhere e.g. to populate a country dropdown - see example, or to modify - see example. Note that any modifications must be done before initialising the plugin.

var countryData = $.fn.intlTelInput.getCountryData();

Returns an array of country objects:

[{
  name: "Afghanistan (‫افغانستان‬‎)",
  iso2: "af",
  dialCode: "93"
}, ...]

loadUtils
Note: this is only needed if you're lazy loading the plugin script itself (intlTelInput.js). If not then just use the utilsScript option.
Load the utils.js script (included in the lib directory) to enable formatting/validation etc. See Utilities Script for more information.

$.fn.intlTelInput.loadUtils("build/js/utils.js");

setCountryData [REMOVED]
Set the plugin's country data. This method was removed because it makes much more sense to just use getCountryData and then modify that (see example) instead of having to generate the whole thing yourself - the country data has become increasingly complicated and for each country we now have five properties: the name, iso2 country code, international dial code, priority (in case two countries have the same international dial code), and finally a list of area codes used in that country - see data.js for more info.

Events

You can listen for the following events on the input.

countrychange
This is triggered when the user selects a country from the dropdown.

$("#phone").on("countrychange", function(e, countryData) {
  // do something with countryData
});

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.

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 and setNumber
  • Validation with isValidNumber, getNumberType and getValidationError 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 the nationalMode option

International number formatting/validation is hard (it varies by country/district, and we currently support ~230 countries). The only comprehensive solution I have found is libphonenumber, from which I have precompiled the relevant parts into a single JavaScript file and included in the lib directory. Unfortunately even after minification it is still ~215KB, but if you use the utilsScript option then it will only fetch the script when the page has finished loading (to prevent blocking). If size is not a concern, then you can manually include the script yourself however you like, and as long as it has loaded before you initialise the plugin then it should work fine.

To recompile the utilities script yourself, see the comments at the top of src/js/utils.js.

Troubleshooting

Submitting the full international number when in nationalMode
If you're submitting the form using Ajax, simply use getNumber to get the number before sending it. If you're using the standard form POST method, you have two options. The easiest thing to do is simply update the input value using getNumber in a submit handler:

$("form").submit(function() {
  myInput.val(myInput.intlTelInput("getNumber"));
});

But this way the user will see their value change when they submit the form, which is weird. A better solution would be to update the value of a separate hidden input, and then read that POST variable on the server instead. See an example of this solution here.

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>.

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](https://bugs.webkit.org/showbug.cgi?id=141822) 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: .intl-tel-input .iti-flag .arrow {border: none;}_

Contributing

See the contributing guide.

Attributions

changelog

v10.0.7 (2017-01-21)

v10.0.6 (2017-01-11)

v10.0.5 (2017-01-10)

v10.0.4 (2017-01-07)

v10.0.3 (2017-01-07)

v10.0.2 (2016-12-15)

v10.0.1 (2016-12-14)

v10.0.0 (2016-12-10)

  • rename numberType option to placeholderNumberType
  • rename formatOnInit to formatOnDisplay

v9.2.7 (2016-12-07)

v9.2.6 (2016-12-02)

v9.2.5 (2016-11-30)

v9.2.4 (2016-10-31)

v9.2.3 (2016-10-11)

v9.2.2 (2016-10-07)

v9.2.1 (2016-10-07)

v9.2.0 (2016-10-01)

  • separate allowDropdown and separateDialCode options
  • make defaults object accessible from outside
  • bug fixes

v9.1.0 (2016-09-29)

  • updated autoPlaceholder option to accept "off", "polite" and "aggressive"

v9.0.3 (2016-07-14)

v9.0.0 (2016-06-11)

  • BREAKING CHANGE: removed 2nd arg from setNumber
  • optimize PNGs
  • update libphonenumber to v7.3.2
  • remove cookie stuff (easy to do yourself)
  • added support for jquery 3
  • added kosovo

v8.5.2 (2016-04-27)

v8.5.0 (2016-04-19)

  • autoHideDialCode now works on submit as well

v8.4.7 (2016-03-09)

v8.4.6 (2016-03-09)

v8.4.5 (2016-03-06)

v8.4.3 (2016-02-23)

v8.4.0 (2016-02-19)

  • added formatOnInit option (defaults to true)

v8.3.1 (2016-02-19)

v8.3.0 (2016-02-18)

  • bug fixes (along with lots more tests)
  • re-added getExtension method, which now uses libphonenumber internally for more reliable results

v8.2.0 (2016-02-17)

  • added separateDialCode option

v8.1.0 (2016-02-15)

  • added allowDropdown option (defaults to true)

v8.0.1 (2016-02-15)

v8.0.0 (2016-02-11)

  • removed autoFormat functionality - see issue 346
  • removed allowExtensions and getExtension as a result
  • country dropdown now a custom full-screen popup on mobile
  • rename country-change event to countrychange for consistency
  • trigger countrychange event whenever the country changes

v7.1.0 (2016-01-11)

  • set autoFormat option to default to false due to known UX issue
  • trigger custom country-change event when user selects a country

v7.0.0 (2015-12-20)

  • changed loadUtils to be a static method
  • rename selectCountry to setCountry
  • rename defaultCountry to initialCountry
  • lots of tidy up and bug fixes

v6.4.0 (2015-10-15)

  • added excludeCountries option

v6.3.0 (2015-10-11)

  • added dropdownContainer option

v6.2.0 (2015-09-27)

v6.1.0 (2015-09-16)

  • Made Sass variables overridable
  • Updated libphonenumber to v7.0.11
  • Added version number into js
  • Added customPlaceholder option
  • Added CommonJS support
  • Lots of bug fixes

v6.0.0 (2015-06-05)

  • BREAKING: Updated defaultCountry=auto system to use new geoIpLookup function option

v5.8.0 (2015-03-14)

  • if set defaultCountry=auto and use jquery-cookie plugin, then store the loaded country code in a cookie for future use
  • other bug fixes

v5.7.0 (2015-03-03)

  • setNumber now accepts a 2nd format arg (only works for valid numbers)

v5.6.0 (2015-03-02)

  • new wikimedia commons flag icons

v5.5.0 (2015-02-28)

  • return a deferred object, so dev can use .done() to know when the plugin has finished initialising

v5.4.0 (2015-02-22)

  • use a native select for dropdown on mobile

v5.3.0 (2015-02-21)

  • retina flag icons

v5.2.0 (2015-02-21)

  • on clear input: default to last selected flag
  • other bug fixes

v5.1.0 (2015-02-06)

  • Added allowExtensions option - defaults to false

v5.0.0 (2015-01-20)

  • Empty state for flag when invalid dial code
  • Removed preventInvalidNumbers as was wrongly using libphonenumber's AsYouTypeFormatter, which was broken and they explicitly said shouldn't be used for that
  • Added default flash styling on autoFormat's invalid char event, which can easily be overridden

v4.0.0 (2015-01-15)

  • Defaulted nationalMode to true because it's a better experience for the user
  • Rename getCleanNumber to getNumber and take a format type arg
  • Remove responsiveDropdown option and just trigger automatically on small screens
  • Remove useless setCountryData method
  • Change flag CSS from .intl-tel-input .flag to .iti-flag to reduce CSS filesize and allow easier re-use

v3.8.0 (2015-01-11)

  • Added preventInvalidNumbers option
  • Set autocomplete="off" on input to prevent inconsistencies
  • Support readonly inputs
  • Trigger input event when autoFormat is enabled

v3.7.0 (2014-11-02)

  • ipinfoToken option, which is required for ipinfo https support
  • bug fixes

v3.6.0 (2014-10-09)

  • autoFormat feature: trigger custom invalidkey event on invalid key press so can give user feedback
  • tweak autoFormat delete key behaviour: no reformat if delete and cursorAtEnd, never add format suffix on delete - this should also fix an IE8 issue with autoFormat

v3.5.0 (2014-10-03)

  • Added numberType option

v3.4.0 (2014-09-29)

  • Can now set defaultCountry to "auto"

v3.3.0 (2014-09-28)

  • Added public method getValidationError
  • Updated libphonenumber
  • Fail gracefully if call selectCountry with invalid countryCode

v3.2.0 (2014-09-27)

  • Added loadUtils method
  • Bug fixes

v3.1.0 (2014-09-21)

  • Added public method getNumberType
  • Added public method getCleanNumber
  • Added support for maxlength attribute on the input
  • autoFormat now prevents further input when the formatting fails i.e. no longer a potentially valid number
  • Other bug fixes

v3.0.0 (2014-09-07)

  • isValidNumber now works in nationalMode
  • country-specific placeholders, which auto update (and also work in nationalMode)
  • autoFormat now works for all countries as now uses libphonenumber (and now works in nationalMode too)
  • cursor-to-end on tab (if autoHideDialCode enabled)
  • handle North American Numbering Plan area codes (e.g. change to Canada if type "+1204")
  • removed static formatNumber method as doesnt really make sense as relies on an instance of the plugin to load the utils script
  • reduced filesize of data.js by generating allCountryCodes on the fly, and removing some obscure countries
  • reduced filesize of flags.png by removing unused flags
  • lots of bug fixes and new tests written

v2.0.0 (2014-07-13)

  • Automatically format the number as the user types
  • Full type-to-search in dropdown
  • Removed defaultStyling option as hadn't seen anyone using it and it felt like bloat
  • Removed dialCodeDelimiter option as superseded by autoFormat option
  • Lots of other bug fixes and improvements

v1.2.0 (2014-07-02)

  • reduced filesize from country data
  • compress css to reduce filesize
  • fixes to country data (canada and Caribbean Netherlands)
  • more tests
  • added public destroy method
  • removed redundant defaultStyling=none option
  • added responsiveDropdown option
  • full type to search
  • lots of bug fixes

v1.1.0 (2014-03-03)

  • validation script now waits for the load event
  • fixed issue with specificity on critical input styling
  • when auto-inserting DC, if user hits + then assume typing new number so wipe the DC
  • added allowNational argument for public isValidNumber method
  • fixed issue with unbinding keypress event
  • selecting another country then deleting the dial code no longer takes you back to the default country
  • replaced americaMode with more generic nationalMode

v1.0.0 (2014-02-24)

  • fixed issue on IE: selecting flag puts cursor at beginning
  • position the dropdown above the input depending on layout/scroll
  • added validation via the validationScript option

v0.9.17 (2014-02-22)

  • fixed issue with autoHideDialCode option, where sometimes clicking the input to focus it would leave the cursor in the middle of the dial code (or to the left of it)

v0.9.16 (2014-02-09)

v0.9.15 (2014-02-09)

  • improved vertical centering and made arrow smaller
  • renamed option to dialCodeDelimiter
  • 2 new examples (plus syntax highlighting on examples)

v0.9.14 (2014-02-01)

  • fixed issue in firefox: vertical margin on input breaks alignment
  • CSS tidyup / alignment fixes
  • JS abstraction / tidyup
  • arrow now points up while dropdown open
  • added title attribute to selected flag (try hovering the selected flag!)
  • added getSelectedCountryData public method

v0.9.13 (2014-01-21)

  • fixed regression: input with vertical margin breaks flag alignment

v0.9.12 (2014-01-21)

  • fixed issue with default delimiter and autoHideDialCode option

v0.9.11 (2014-01-21)

  • allow dial code delimiter to be overridden
  • Wrap in UMD (so that it supports AMD)
  • fixed issue: enter on dropdown submits form
  • improved default styling
  • new flags
  • updated country data to show 24 more countries
  • abstracted lots of new functions from plugin init method

v0.9.10 (2014-01-15)

  • Bug fixes

v0.9.9 (2014-01-13)

v0.9.8 (2014-01-13)

  • Examples

v0.9.7 (2014-01-13)

  • fire change event on the input when changing countries
  • fixed issue where dial codes were ignored if they had a space in
  • fixed issue: changing flag doesnt update number when dial code contains space/dot etc
  • lots more tests
  • disabled dropdown/hover states when input disabled
  • support inputs of any height
  • fixed issue where hitting enter to select a list item didnt close the dropdown
  • updated defaultStyling option to allow positioning selected flag outside input

v0.9.6 (2013-12-16)

  • Removed initialDialCode option as made redundant by autoHideDialCode option
  • Added defaultCountry option

v0.9.5 (2013-11-25)

  • Option initialDialCode now defaults to false
  • Added option autoHideDialCode, which defaults to true
  • Added public method setNumber
  • Added static methods getCountryData and setCountryData

v0.9.4 (2013-10-27)

v0.9.3 (2013-10-24)

  • Fixed issues with instantiating the plugin on multiple inputs
  • Added defaultStyling option
  • Added localised country names in brackets

v0.9.2 (2013-10-13)

  • Added some tests.