Somthing Went Wrong Try Again Phone Number

    How to build international phone number input in HTML and JavaScript

    Phone numbers are standardized in an international format known as Due east.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 y'all don't have to store land codes and phone numbers in 2 separate database columns.

    However, you probably don't want your users to have to blazon 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, only it has a lot of additional configuration options that you tin explore in the documentation.

    The plugin provides a land code drop down with nice flags to stand for different countries. It also processes the subscriber or "national format" number to normalize user input that could include spaces, parentheses, dashes, and more.

    Phone number input field showing the result in E.164 format

    Embed the intl-tel-input plugin in your code

    Nosotros're going to proceed things pretty simple here and starting time with some vanilla HTML and JavaScript. Create a new file called index.html and add together the following code:

                      <!DOCTYPE html> <html lang="en">  <head>    <title>International phone input</title>    <meta proper name="viewport" content="width=device-width, initial-calibration=1" />    <link rel="stylesheet" href="styles.css" />    <link      rel="stylesheet"      href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/css/intlTelInput.css"    />    <script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.viii/js/intlTelInput.min.js"></script>  </head>  <trunk>  </body> </html>                                  

    This pulls in the CDN versions of the plugin's CSS and JS, which helps us display the country code drib down and process the phone numbers. I'm using v17.0.8, but you can find the latest version by checking out the tags. You tin likewise install the plugin with a bundler or download and host the source code yourself.

    For nicer styles, create a new file in the same binder called styles.css and add the CSS found here.

    Next, add the form that volition include the telephone number input. Inside the body tags of the index.html file, add together the post-obit HTML:

                      <div class="container">  <grade id="login" onsubmit="procedure(event)">    <p>Enter your phone number:</p>    <input id="telephone" type="tel" name="phone" />    <input type="submit" class="btn" value="Verify" />  </form> </div>                                  

    If you load this file into a browser at this point, you'll see the form field but no formatting yet, nosotros even so need to initialize the plugin.

    phone number input field that has no special formatting

    Initialize the intl-tel-input plugin

    Add a script tag below the body but within the HTML and add the post-obit initialization lawmaking:

                                          <!-- ^^  form code  ^^ -->  </body>  <script>    const phoneInputField = document.querySelector("#telephone");    const phoneInput = window.intlTelInput(phoneInputField, {      utilsScript:        "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.viii/js/utils.js",    });  </script> </html>                                  

    The utilsScript is technically optional, simply it provides a lot of really useful functionality similar state specific placeholders and the Due east.164 formatting we'll use below.

    Reload the page and y'all should come across the country picker and a placeholder now.

    phone number input field with US flag and country code dropdown, including placeholder text for a phone number

    Process the phone number input to get the international format

    Add together an alert banner below our course. These will help us display our results.

                                          </form>  <!-- ^^  grade lawmaking  ^^ -->  <div form="warning warning-info" style="display: none;"></div>                                  

    Side by side, add together a function to handle the form submit. Within your <script> tag and after the plugin initialization, add the following:

                      const info = document.querySelector(".alarm-info");  function process(event) {  effect.preventDefault();   const phoneNumber = phoneInput.getNumber();   info.style.display = "";  info.innerHTML = `Phone number in E.164 format: <stiff>${phoneNumber}</strong>`; }                                  

    The nearly of import role hither is phoneInput.getNumber() — this is the plugin code that converts the selected country lawmaking and user input into the international format.

    Reload the page, enter a telephone number and you should meet the international format!

    phone number input with successful result in E.164 format

    Bonus: Make the plugin location-enlightened

    The plugin defaults to the U.s., but you're probably implementing this because yous have global users. You tin can update the settings to default to the user'due south location based on their IP address.

    Sign upwards for a free account at IPinfo and grab your access token. You could use a different IP accost API for this if you have a dissimilar one you lot prefer. Add the following function at the acme of your <script> tag earlier defining the phoneInputField object:

                      function getIp(callback) {  fetch('https://ipinfo.io/json?token=<your token>', { headers: { 'Accept': 'application/json' }})    .then((resp) => resp.json())    .take hold of(() => {      return {        country: 'us',      };    })    .then((resp) => callback(resp.country)); }                                  

    And then update the intl-tel-input initialization to include two parameters: initialCountry: "auto" and geoIpLookup: getIp.

                      const phoneInput = window.intlTelInput(phoneInputField, {  initialCountry: "auto",  geoIpLookup: getIp,  utilsScript:    "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js", });                                  

    Now if I set my VPN to Austria, the plugin will update the default state

    phone number input showing the austrian flag

    Bonus: Add preferred countries

    I of my other favorite features is the "preferred countries" setting, which allows yous to specify countries to announced at the elevation of the list. For this example I've identified that almost of my users are in the Usa, Colombia, India, and Federal republic of germany and prioritized those options.

    phone number input showing four preferred countries at the top of a dropdown list

    You lot can update this setting where you initialize the plugin by adding an array of preferredCountries in ISO 3166-ane alpha-2 code format:

                      const phoneInput = window.intlTelInput(phoneInputField, {   preferredCountries: ["us", "co", "in", "de"],   utilsScript:     "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.viii/js/utils.js", });                                  

    Validate phone number input

    You might notice that this form doesn't actually prevent any invalid phone numbers even so. You tin follow along this mail service on how to validate phone number input so nosotros don't have people submitting things similar this:

    Invalid phone number input

    All-time practices for phone verification

    Yous definitely want to normalize phone numbers in East.164 format, but if yous plan on storing those numbers yous likewise will want to perform a telephone verification. Telephone verification helps ensure that the user didn't accidentally blazon in the incorrect number, that they have control over the number they're associating with their account, and that you're non spamming the wrong person - you get the idea. Luckily Twilio's Verify API makes information technology easy to do phone verification via SMS or phonation calling. Bank check out this project on our Code Exchange to learn how to implement ane-time passcodes (yous're halfway there with the phone number input!).

    You might also be interested in:

    • Twilio Lookup API documentation
    • Serverless telephone verification with Twilio Verify
    • How to incentivize users to enable 2FA
    • How to build a fast checkout with SMS verification using Stripe and Twilio

    Questions about telephone number input and verification? Y'all tin find me on Twitter @kelleyrobinson. I can't wait to see what you lot build.

younghingred.blogspot.com

Source: https://www.twilio.com/blog/international-phone-number-input-html-javascript

0 Response to "Somthing Went Wrong Try Again Phone Number"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel