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.

4 Form Design UX Tips You Should Know (With Examples)

4 Form Design UX Tips You Should Know (With Examples)

We tend to think about forms as simply a means to collect user data, but they are also…Read more

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

Intro Into HTML5 Constraint Validation

Intro Into HTML5 Constraint Validation

Interactive websites and applications can’t be imagined without forms that enable us to connect with our users, and…Read more



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s