Top Related Projects
Input Mask plugin
Input Mask plugin
A jQuery Plugin to make masks on form fields and HTML elements.
jQuery Masked Input Plugin
Input mask for React, Angular, Ember, Vue, & plain JavaScript
Quick Overview
Cleave.js is a lightweight JavaScript library that helps format input fields in real-time as users type. It supports various input types such as credit card numbers, phone numbers, date fields, and numeric values, providing instant visual feedback and improving data entry accuracy.
Pros
- Easy to implement with minimal setup required
- Supports multiple input formats and customizable patterns
- Works with both vanilla JavaScript and popular frameworks like React, Angular, and Vue
- Lightweight and has no dependencies
Cons
- Limited to input field formatting, not suitable for complex form validation
- Some users report issues with mobile device compatibility
- Occasional conflicts with other JavaScript libraries or form validation tools
- Limited built-in localization support for certain formats
Code Examples
- Basic credit card formatting:
new Cleave('.credit-card-input', {
creditCard: true
});
- Custom date formatting:
new Cleave('.date-input', {
date: true,
datePattern: ['Y', 'm', 'd']
});
- Phone number formatting with a custom pattern:
new Cleave('.phone-input', {
phone: true,
phoneRegionCode: 'US',
prefix: '+1 ',
delimiter: '-'
});
- Numeric input with thousand separators:
new Cleave('.numeric-input', {
numeral: true,
numeralThousandsGroupStyle: 'thousand'
});
Getting Started
- Include Cleave.js in your project:
<script src="https://cdn.jsdelivr.net/npm/cleave.js@1.6.0/dist/cleave.min.js"></script>
- Add an input field to your HTML:
<input type="text" class="my-input">
- Initialize Cleave.js on your input field:
document.addEventListener('DOMContentLoaded', function() {
new Cleave('.my-input', {
// Add your desired options here
creditCard: true
});
});
This example sets up credit card formatting for the input field. Adjust the options based on your specific formatting needs.
Competitor Comparisons
Input Mask plugin
Pros of Inputmask
- More extensive feature set, including support for date, time, and numeric inputs
- Highly customizable with a wide range of options and aliases
- Active development and regular updates
Cons of Inputmask
- Steeper learning curve due to its complexity
- Larger file size, which may impact page load times
- More dependencies and potential compatibility issues
Code Comparison
Cleave.js:
new Cleave('.input-phone', {
phone: true,
phoneRegionCode: 'US'
});
Inputmask:
Inputmask({
mask: '(999) 999-9999',
placeholder: ' '
}).mask('.input-phone');
Both libraries offer similar functionality for basic input masking, but Inputmask provides more advanced options for complex scenarios. Cleave.js focuses on simplicity and ease of use, while Inputmask offers greater flexibility and customization.
Cleave.js is lightweight and straightforward, making it ideal for projects with simple input formatting needs. Inputmask, on the other hand, is better suited for applications requiring extensive input validation and formatting across various data types.
When choosing between the two, consider your project's specific requirements, the level of customization needed, and the trade-offs between simplicity and feature richness.
Input Mask plugin
Pros of Inputmask
- More extensive feature set, including support for date, time, and numeric inputs
- Highly customizable with a wide range of options and aliases
- Active development and regular updates
Cons of Inputmask
- Steeper learning curve due to its complexity
- Larger file size, which may impact page load times
- More dependencies and potential compatibility issues
Code Comparison
Cleave.js:
new Cleave('.input-phone', {
phone: true,
phoneRegionCode: 'US'
});
Inputmask:
Inputmask({
mask: '(999) 999-9999',
placeholder: ' '
}).mask('.input-phone');
Both libraries offer similar functionality for basic input masking, but Inputmask provides more advanced options for complex scenarios. Cleave.js focuses on simplicity and ease of use, while Inputmask offers greater flexibility and customization.
Cleave.js is lightweight and straightforward, making it ideal for projects with simple input formatting needs. Inputmask, on the other hand, is better suited for applications requiring extensive input validation and formatting across various data types.
When choosing between the two, consider your project's specific requirements, the level of customization needed, and the trade-offs between simplicity and feature richness.
A jQuery Plugin to make masks on form fields and HTML elements.
Pros of jQuery-Mask-Plugin
- Lightweight and easy to use, with a simple API
- Supports a wide range of input types and mask patterns
- Extensive documentation and examples available
Cons of jQuery-Mask-Plugin
- Requires jQuery as a dependency
- Limited support for more complex input formatting scenarios
- Less active development compared to Cleave.js
Code Comparison
jQuery-Mask-Plugin:
$('#date').mask('00/00/0000');
$('#phone').mask('(000) 000-0000');
$('#money').mask('000.000.000.000.000,00', {reverse: true});
Cleave.js:
new Cleave('#date', {
date: true,
datePattern: ['m', 'd', 'Y']
});
new Cleave('#phone', {
phone: true,
phoneRegionCode: 'US'
});
new Cleave('#money', {
numeral: true,
numeralThousandsGroupStyle: 'thousand'
});
Both libraries offer similar functionality for input masking and formatting. jQuery-Mask-Plugin uses a more straightforward approach with predefined mask patterns, while Cleave.js provides more granular control over formatting options. Cleave.js also offers additional features like credit card formatting and custom delimiters, making it more versatile for complex input scenarios.
jQuery Masked Input Plugin
Pros of jquery.maskedinput
- Well-established and widely used in legacy jQuery projects
- Supports a variety of predefined masks for common input types
- Simple and straightforward API for basic input masking needs
Cons of jquery.maskedinput
- Requires jQuery as a dependency, which may not be ideal for modern projects
- Less flexible for complex or custom input formatting scenarios
- Not actively maintained, with the last update in 2017
Code Comparison
jquery.maskedinput:
$("#phone").mask("(999) 999-9999");
$("#date").mask("99/99/9999");
cleave.js:
new Cleave('#phone', {
phone: true,
phoneRegionCode: 'US'
});
new Cleave('#date', {
date: true,
datePattern: ['m', 'd', 'Y']
});
Summary
While jquery.maskedinput is a solid choice for jQuery-based projects requiring basic input masking, cleave.js offers a more modern, flexible, and actively maintained solution. cleave.js provides more customization options and doesn't rely on jQuery, making it suitable for a wider range of projects. However, jquery.maskedinput may still be preferred in legacy systems or for developers more comfortable with jQuery syntax.
Input mask for React, Angular, Ember, Vue, & plain JavaScript
Pros of text-mask
- More flexible masking options, including custom mask functions
- Supports multiple input types (text, number, tel)
- Actively maintained with regular updates
Cons of text-mask
- Slightly more complex setup and configuration
- Less built-in formatting options for specific data types (e.g., credit cards)
Code Comparison
text-mask:
import { createTextMaskInputElement } from 'text-mask-core'
const maskedInputElement = createTextMaskInputElement({
inputElement: document.querySelector('#my-input-element'),
mask: ['(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
})
cleave.js:
import Cleave from 'cleave.js'
new Cleave('#my-input-element', {
phone: true,
phoneRegionCode: 'US'
})
Summary
text-mask offers more flexibility and customization options, making it suitable for complex masking requirements. It supports various input types and is actively maintained. However, it may require more setup and configuration compared to cleave.js.
cleave.js provides simpler implementation for common formatting tasks, especially for specific data types like credit cards or phone numbers. It has a more straightforward API but may be less flexible for highly custom masking needs.
Choose text-mask for advanced masking requirements and cleave.js for quick and easy formatting of common data types.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
â ï¸ Deprecated Message
Message: Kindly note that this library has been deprecated. If you are still interested in using Cleave, please explore the new version available at: cleave-zen.
And this is the message from author: https://github.com/nosir/cleave.js/issues/723
Cleave.js
Cleave.js has a simple purpose: to help you format input text content automatically.
Features
- Credit card number formatting
- Phone number formatting (i18n js lib separated for each country to reduce size)
- Date formatting
- Numeral formatting
- Custom delimiter, prefix and blocks pattern
- CommonJS / AMD mode
- ReactJS component
- AngularJS directive (1.x)
- ES Module
TL;DR the demo page
Why?
The idea is to provide an easy way to increase input field readability by formatting your typed data. By using this library, you won't need to write any mind-blowing regular expressions or mask patterns to format input text.
However, this isn't meant to replace any validation or mask library, you should still sanitize and validate your data in backend.
Installation
npm
npm install --save cleave.js
CDN
cleave.js is available on jsDelivr and on cdnjs.com
old school
Grab file from dist directory
Usage
Simply include
<script src="cleave.min.js"></script>
<script src="cleave-phone.{country}.js"></script>
cleave-phone.{country}.js
addon is only required when phone shortcut mode is enabled. See more in documentation: phone lib addon section
Then have a text field
<input class="input-phone" type="text" />
Now in your JavaScript
var cleave = new Cleave('.input-phone', {
phone: true,
phoneRegionCode: '{country}',
})
.input-element
here is a unique DOM element. If you want to apply Cleave for multiple elements, you need to give different CSS selectors and apply to each of them, effectively, you might want to create individual instance by a loop, e.g. loop solution
More examples: the demo page
CommonJS
var Cleave = require('cleave.js');
require('cleave.js/dist/addons/cleave-phone.{country}');
var cleave = new Cleave(...)
AMD
require(['cleave.js/dist/cleave.min', 'cleave.js/dist/addons/cleave-phone.{country}'], function (Cleave) {
var cleave = new Cleave(...)
});
ES Module
// Rollup, WebPack
import Cleave from 'cleave.js';
var cleave = new Cleave(...)
// Browser
import Cleave from 'node_modules/cleave.js/dist/cleave-esm.min.js';
var cleave = new Cleave(...)
TypeScript
Types are contributed by the community and are available via npm install --save-dev @types/cleave.js
. Once installed, you can import Cleave like the following:
import Cleave = require('cleave.js')
Types for the React-component are also available and can be imported in the same way.
import Cleave = require('cleave.js/react')
ReactJS component usage
import React from 'react'
import ReactDOM from 'react-dom'
import Cleave from 'cleave.js/react'
Then in JSX:
class MyComponent extends React.Component {
constructor(props, context) {
super(props, context)
this.onCreditCardChange = this.onCreditCardChange.bind(this)
this.onCreditCardFocus = this.onCreditCardFocus.bind(this)
}
onCreditCardChange(event) {
// formatted pretty value
console.log(event.target.value)
// raw value
console.log(event.target.rawValue)
}
onCreditCardFocus(event) {
// update some state
}
render() {
return (
<Cleave
placeholder='Enter your credit card number'
options={{ creditCard: true }}
onFocus={this.onCreditCardFocus}
onChange={this.onCreditCardChange}
/>
)
}
}
As you can see, here you simply use <Cleave/>
as a normal <input/>
field
- Attach HTML
<input/>
attributes - Pass in the custom
options
prop - Add ReactJS
onChange
event listener
Advanced usage:
- How to pass default value
- How to get ref of cleave instance and call methods
- How to update raw value
- How to get ref of the input field
- How to use it with redux form
Usage for Webpack
, Browserify
and more in documentation: ReactJS component usage
AngularJS directive usage
First include the directive module:
<script src="cleave.js/dist/cleave-angular.min.js"></script>
<script src="cleave.js/dist/addons/cleave-phone.{country}.js"></script>
And in your model:
angular
.module('app', ['cleave.js'])
.controller('AppController', function ($scope) {
$scope.onCreditCardTypeChanged = function (type) {
$scope.model.creditCardType = type
}
$scope.model = {
rawValue: '',
}
$scope.options = {
creditCard: {
creditCard: true,
onCreditCardTypeChanged: $scope.onCreditCardTypeChanged,
},
}
})
Then easily you can apply cleave
directive to input
field:
<div ng-controller="AppController">
<input
ng-model="model.rawValue"
ng-whatever="..."
type="text"
placeholder="Enter credit card number"
cleave="options.creditCard"
/>
</div>
More usage in documentation: Angular directive usage
Use in VueJs
While this package does not have an official support for use in VueJs. This can be done in few simple steps. Please check here
jQuery fn usage
Please check here
Playground
Documentation
Run tasks
npm install
Build assets
gulp build
Run tests
gulp test
Lint
gulp eslint
Publish (build, tests & lint)
gulp publish
For contributors, please run
gulp publish
to ensure your PR passes tests and lint, also we have a not in the plan list you may concern.
Get in touch
- Twitter: @rison
References
- Payment credit card number IIN https://en.wikipedia.org/wiki/Payment_card_number#Issuer_identification_number_.28IIN.29
- Google phone numbers formatting https://github.com/googlei18n/libphonenumber
- Decimal mark and thousands separating style https://en.wikipedia.org/wiki/Decimal_mark#Examples_of_use
Licence
Cleave.js is licensed under the Apache License Version 2.0
- Google libphonenumber is included under its Apache License Version 2.0
Top Related Projects
Input Mask plugin
Input Mask plugin
A jQuery Plugin to make masks on form fields and HTML elements.
jQuery Masked Input Plugin
Input mask for React, Angular, Ember, Vue, & plain JavaScript
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot