What is Cleave.js?

Forms are an integral part of every website; they can be used to collect user data, feedback, and user authentication. As developers, we aim to make users' experiences on a website as good as possible and make things easier for ourselves. We can achieve this by formatting input fields in a real-time model. This increases users' readability and enables developers to minimize errors as they have a data pattern pulled across the application. Cleave.js is used for this purpose.

Cleave.js is a JavaScript library that easily formats input fields as we type. It allows us to specify a pattern or mask to control the data pattern entered into an input field. Cleave.js also helps increase the readability of our input field. It is easy to use and lightweight, and works with all modern browsers.

What input fields can we format with Cleave.js?

We can format different input fields with Cleave.js. The primary types of formatting in Cleave.js are as follows:

  • Credit card number formatting

  • Phone number formatting

  • Date formatting

  • Numerical formatting

  • Custom delimiter, prefix, and block patterns

Cleave.js also allows formatting monetary values by adding currency symbols and formatting number inputs with decimal places, thousands of separators, and more. Additionally, it allows for masking input fields, which can be used to format sensitive information such as passwords and social security numbers.

How to use Cleave.js in a React application

Installation

We must install a React.js application and a Cleave.js library to get started.

We can install the Cleave.js library by running the following commands in the terminal:

// NPM
npm install cleave.js
//YARN
yarn add cleave.js

Example

Let's create a payment form to learn more about this:

const reportWebVitals = onPerfEntry => {
  if (onPerfEntry && onPerfEntry instanceof Function) {
    import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
      getCLS(onPerfEntry);
      getFID(onPerfEntry);
      getFCP(onPerfEntry);
      getLCP(onPerfEntry);
      getTTFB(onPerfEntry);
    });
  }
};

export default reportWebVitals;

Explanation

  • Line 14: We'll import the necessary modules needed from the React and Cleave.js library. The useState hook from React is used to manage the state of the form fields, and the Cleave component from the Cleave.js library is used to format the input fields. We also import style.css for styling our payment form.

  • Lines 6–12: We create a functional component that renders the payment form, and we'll also define five state variables setting each variable initially to an empty string using the useState hook. The associated set functions are used to update the state of an input when the user enters data.

  • Lines 20–29: We create a label element and a Cleave component. The Cleave component is used to format the input field for the creditCardNumber. The options prop is set to { creditCard: true } to format the input as a credit card number. The value prop is set to {creditCardNumber} so that the input field is initialized with the current value of the creditCardNumber state variable.

  • Lines 33–41: We create a label element and a Cleave component; the Cleave component is used to format the input field for the expiration date. We set the options prop to format the input as a date so that it accepts two digits each for the month, year, and day. We also set the value to {expirationDate} so that the input field is initialized with the current value of the expirationDate state variable and the onChange prop is set to an arrow function that calls the setExpirationDate function with the value entered by the user, updating the state of the expirationDate variable.

  • Lines 46–54: We create a label element and a Cleave component. The Cleave component is used to format the input field of cvv. The options prop is set to { blocks: [3], numericOnly: true } to format the input as a numeric input of length 3. The value prop is set to {cvv} so that the input field is initialized with the current value of the cvv state variable and the onChange prop is set to an arrow function that calls the setCvv function with the value entered by the user, updating the state of the cvv variable.

  • Lines 61–70: We create a label element and a Cleave component. The Cleave component is used to format the input field of time. The options prop is set to time: true which formats the input as a time value. The timePattern: ["h","m"] formats the time value as hours and minutes. The value prop is set to the current value of the time state variable and the onChange prop is used to update the time state variable with the new value as the user types into the input element.

  • Lines 71–87: We create a custom delimeter, prefix, and block patterns for our phone input field. We set the option prop to prefix:"+234" which adds a prefix of +234 to the input value. The numericOnly: true accepts only numeric input. We set blocks to blocks: [4,3,4] which formats the input into groups of 4 digits, 3 digits, and 4 digits. The delimiters: [" -"] separates the input into groups with a " -" delimiter. The ref prop is used to create a reference to the input element, and the value prop is set to the current value of the phoneNumber state variable. The onChange prop is used to update the phoneNumber state variable with the new value as the user types into the input element.

Conclusion

We successfully formatted our credit card number, date, time, numerical inputs, and phone number with Cleave.js. It saved us a lot of time and offered user satisfaction.

Learn more about what can be achieved with Cleave.js in the official documentation.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved