Cleave.js is a JavaScript library that simplifies the process of formatting input fields on-the-fly. It supports various formats such as phone numbers, credit card numbers, dates, and custom patterns, enhancing data accuracy and user experience.
Installation
Using CDN
Add Cleave.js to your project using a CDN:
Using npm
Install via npm:
Import it in your JavaScript file:
Downloading
Download Cleave.js from GitHub and include it in your project:
Basic Usage
Cleave.js is initialized by creating a new instance and passing configuration options.
Phone Number Formatting
US Phone Number
International Phone Number
Credit Card Formatting
Basic Credit Card Formatting
Credit Card with Specific Types
Date Formatting
MM/DD/YYYY
DD-MM-YYYY
Numeric Formatting
Currency Formatting
Percentage Formatting
Custom Patterns
Example: Custom Pattern
This will format the input as 123-456-7890.
Advanced Features
Dynamic Input Mask
You can change the format of the input dynamically based on user interactions or other conditions.
Example: Switching Phone Masks
Handling Events
Cleave.js allows you to listen to specific events, such as changes in the input value.
Example: Input Change Event
Integration with Frameworks
Cleave.js can be easily integrated with popular frameworks like React and Vue.js.
React Integration
Vue.js Integration
Customizing Cleave.js
Cleave.js allows for significant customization beyond basic formatting.
Custom Delimiters and Prefixes
You can customize the delimiters and prefixes to fit specific needs.
Example: Custom Delimiters
Masking with Multiple Formats
Cleave.js supports multiple formats in a single input field.
Example: Mixed Formats
Troubleshooting and Best Practices
Common Issues
Formatting Not Applied: Ensure that Cleave.js is properly included in your project and that you are targeting the correct element.
Incorrect Formats: Verify that the options provided match the desired format and that any dynamic updates are correctly applied.
Best Practices
Minimize Re-renders: Avoid unnecessary re-renders in frameworks like React to maintain performance.
Validate Inputs: Always validate user input on the server side in addition to client-side formatting.
Conclusion
Cleave.js is an invaluable tool for handling input formatting across various scenarios. By leveraging its extensive options and integration capabilities, you can enhance user experience and ensure data integrity in your applications.