cleave-js-phone-tutorial-thumbnail
Javascript Web Development

Auto Format Phone Number based on Country with JavaScript

We’re still with Cleave.js. In this post, I’m going to show you how to use Cleave.js to mask and format the phone number on the input field automatically according to the user’s country. Let’s check it out!

Setup

Download the latest release from github and open the package. Copy over Cleave.js core file inside the dist folder to your web directory (You can choose between full or minified version)

Then copy the cleave-phone country add-on file. The library has separated the phone format by country to reduce the file size. So if you expected your page to format just one or only few countries, just pick only countries you need. Otherwise, there is a i18n version which included all countries in one big file. (i18n is an abbreviation for “Internationalization”)

cleave-js-format-phone-number-5

I’m going to use i18n version for this tutorial.

Usage

Now I already have an input field and a drop down with few countries for testing. I’m going to include the core library file and the phone addon file.

<input id="input-phone" type="text"/>
<select id="select-country">
     <option value="US">US</option>
     <option value="GB">GB</option>
     <option value="SG">SG</option>
     <option value="TH">TH</option>   
</select>
<script src="cleave.js"></script>
<script src="cleave-phone.i18n.js"></script>

Next create a cleave.js instance and pass the input element, follow by an option object. Set the phone property to true and set the phoneRegionCode to your default country of choice.

var cleave = new Cleave('#input-phone', {
            phone:true,
            phoneRegionCode: 'US'
        });

I will add a change event listener to the country drop down to set the new region code when the user pick the new country. Use setPhoneRegioncode method and pass the current selection. I’ll also use setRawValue to clear the input field.

$('#select-country').change(function(){
    cleave.setPhoneRegionCode(this.value);
    cleave.setRawValue('');
});

Ok, That’s it. Testing time.

Testing

Let’s try entering the phone number from various countries

cleave-js-format-phone-number-1 cleave-js-format-phone-number-2 cleave-js-format-phone-number-3 cleave-js-format-phone-number-4

So that’s all for this post. Hope it helps. If you love this tutorial, please like or subscribe to our Youtube Channel or follow us on Facebook to stay tune for more. Don’t forget to check our JavaScript Realtime Chart Tutorial also 🙂

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *

error: