Format Input Fields Automatically with Cleave.js

Think about all the different input fields that require a formatted structure. Phone numbers, credit cards, birth dates, street addresses… they all have their own unique patterns.

It’s easy enough to leave these fields alone and trust the user. But it might be better to use Cleave.js, a free vanilla JavaScript plugin to help you automatically format input fields.

cleave.js inputs

HTML5 comes with its own set of inputs related to data patterns such as telephone numbers. With Cleave, you can take this to the next level with customized inputs that automatically format text as it’s typed.

By default, the plugin supports five basic text patterns:

  1. Credit card numbers
  2. Phone numbers
  3. Dates
  4. Numeric styling (with commas)
  5. Custom input fields

That last choice is the coolest one because you can make your own custom data patterns from scratch. Cleave doesn’t force you to follow any strict methodology.

Instead, it gives you the tools to build your own inputs with optional support for React and Angular components. It also supports all major browsers and should match support for legacy browsers along with jQuery.

cleavejs custom options

Note this isn’t a tough plugin to set up. You target whatever ID or class you have on your input field and pass that into a new Cleave instance. Here’s a sample snippet:

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

However, while Cleave may be easy to set up, it has a lot of custom features you can toy with.

All of the documentation is hosted inside the repo, so you’ll need to browse the GitHub page to find all the different methods & options. Specifically, the options page has a lot to go through and might take a while to find what you want.

Thankfully, Cleave has plenty of live examples you can study and replicate. These examples are also free to download from the GitHub repo. If you want to see more live examples visit the Cleave.js home page or check out this fiddle jam-packed with demos.

WebsiteFacebookTwitterInstagramPinterestLinkedInGoogle+YoutubeRedditDribbbleBehanceGithubCodePenWhatsappEmail