Phone numbers are standardized in an international format known as E.164 which combines country codes and subscriber numbers in a format like this: +14155552671. This format is required by many APIs (including Twilio's) and means that you don't have to store country codes and phone numbers in two separate database columns.
However, you probably don't want your users to have to type in a + sign and country code when they provide their phone number to:
- Register a new account
- Enable SMS 2FA
- Request a callback from customer service
- Sign up for marketing notifications
This blog post will walk through how to build a phone number input field to process and parse phone numbers using basic HTML, JavaScript, and the intl-tel-input
plugin. We'll include recommendations for phone verification and fraud prevention.
You can find the finished code on my GitHub.
What can the intl-tel-input plugin do?
This project makes heavy use of intl-tel-input, a "JavaScript plugin for entering and validating international telephone numbers". I'll cover my usual setup of the plugin, but it has a lot of additional configuration options that you can explore in the documentation.
The plugin provides a country code drop down with nice flags to represent different countries. It also processes the subscriber or "national format" number to normalize user input that could include spaces, parentheses, dashes, and more.
Embed the intl-tel-input plugin in your code
We're going to keep things pretty simple here and start with some vanilla HTML and JavaScript. Create a new file called index.html
and add the following code: