Comprehensive Guide to Cleave.js
Aug 10, 2024
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:
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/cleave.js/dist/addons/cleave-phone.us.css"
/>
<script src="https://cdn.jsdelivr.net/npm/cleave.js@1.6.0/dist/cleave.min.js"></script>
Using npm
Install via npm:
npm install cleave.js
Import it in your JavaScript file:
import Cleave from "cleave.js";
Downloading
Download Cleave.js from GitHub and include it in your project:
<script src="path/to/cleave.min.js"></script>
Basic Usage
Cleave.js is initialized by creating a new instance and passing configuration options.
Phone Number Formatting
US Phone Number
<input type="text" id="phone-us" />
<script>
new Cleave("#phone-us", {
phone: true,
phoneRegionCode: "US",
});
</script>
International Phone Number
<input type="text" id="phone-intl" />
<script>
new Cleave("#phone-intl", {
phone: true,
phoneRegionCode: "ZZ", // ZZ for international format
});
</script>
Credit Card Formatting
Basic Credit Card Formatting
<input type="text" id="credit-card" />
<script>
new Cleave("#credit-card", {
creditCard: true,
});
</script>
Credit Card with Specific Types
<input type="text" id="credit-card-specific" />
<script>
new Cleave("#credit-card-specific", {
creditCard: true,
creditCardStrictMode: true,
creditCardTypes: ["visa", "mastercard"],
});
</script>
Date Formatting
MM/DD/YYYY
<input type="text" id="date-mm-dd-yyyy" />
<script>
new Cleave("#date-mm-dd-yyyy", {
date: true,
datePattern: ["m", "d", "Y"],
});
</script>
DD-MM-YYYY
<input type="text" id="date-dd-mm-yyyy" />
<script>
new Cleave("#date-dd-mm-yyyy", {
date: true,
datePattern: ["d", "m", "Y"],
});
</script>
Numeric Formatting
Currency Formatting
<input type="text" id="currency" />
<script>
new Cleave("#currency", {
numeral: true,
numeralThousandsGroupStyle: "thousand",
});
</script>
Percentage Formatting
<input type="text" id="percentage" />
<script>
new Cleave("#percentage", {
numeral: true,
numeralDecimalMark: ".",
delimiter: ",",
prefix: "% ",
});
</script>
Custom Patterns
Example: Custom Pattern
<input type="text" id="custom-pattern" />
<script>
new Cleave("#custom-pattern", {
blocks: [3, 3, 4],
delimiters: ["-", "-", ""],
});
</script>
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
<input type="text" id="dynamic-phone" />
<button id="change-mask">Change Mask</button>
<script>
const cleave = new Cleave("#dynamic-phone", {
phone: true,
phoneRegionCode: "US",
});
document.getElementById("change-mask").addEventListener("click", () => {
cleave.setPhoneRegionCode("GB"); // Switch to UK phone format
});
</script>
Handling Events
Cleave.js allows you to listen to specific events, such as changes in the input value.
Example: Input Change Event
<input type="text" id="event-phone" />
<script>
const cleave = new Cleave("#event-phone", {
phone: true,
phoneRegionCode: "US",
});
cleave.on("valueChanged", function (e) {
console.log("New value:", e.target.value);
});
</script>
Integration with Frameworks
Cleave.js can be easily integrated with popular frameworks like React and Vue.js.
React Integration
npm install cleave.js react-cleave
import React from "react";
import Cleave from "react-cleave";
function App() {
return (
<div>
<Cleave
className="form-control"
options={{ phone: true, phoneRegionCode: "US" }}
placeholder="Enter phone number"
/>
</div>
);
}
export default App;
Vue.js Integration
npm install cleave.js vue-cleave
import Vue from "vue";
import Cleave from "vue-cleave";
Vue.use(Cleave);
new Vue({
el: "#app",
template: `
<div>
<cleave
v-model="phone"
:options="{ phone: true, phoneRegionCode: 'US' }"
placeholder="Enter phone number"
></cleave>
</div>
`,
data() {
return {
phone: "",
};
},
});
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
<input type="text" id="custom-delimiters" />
<script>
new Cleave("#custom-delimiters", {
blocks: [3, 2, 2, 2],
delimiters: [" ", "/", "/"],
});
</script>
Masking with Multiple Formats
Cleave.js supports multiple formats in a single input field.
Example: Mixed Formats
<input type="text" id="mixed-format" />
<script>
new Cleave("#mixed-format", {
blocks: [4, 4, 4],
delimiters: [" ", "-"],
});
</script>
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.
For further details, refer to the official Cleave.js documentation and explore the library's full range of features.