Home

Awesome

credit-card-input-mask

forked from braintree/restricted-input

Allow restricted character sets in input elements.

Install

$ npm install --save credit-card-input-mask

Usage

import CreditCardInputMask from "credit-card-input-mask";

const formattedCreditCardInput = new CreditCardInputMask({
  element: document.querySelector("#credit-card"),
  pattern: "{{9999}} {{9999}} {{9999}} {{9999}}",
});

Demo

Patterns

Patterns are a mixture of Placeholders and PermaChars.

Placeholder

A Placeholder is the part of the pattern that accepts user input based on some restrictions. A placeholder is defined in the pattern using two open curly brackets, the placeholder, followed by two closing curly brackets e.g. {{Abc123}}.

The patterns a Placeholder can be are:

PermaChar

A PermaChar is the part of the pattern that is automatically inserted. PermaChars are defined in the pattern as any characters other than Placeholders.

Example patterns

Some example patterns with behavior are listed:

Paste Event

If an input is changed via a paste event, you may want to adjust the pattern before input formatting occurs. In this case, pass an onPasteEvent callback:

const formattedCreditCardInput = new RestrictedInput({
  element: document.querySelector('#credit-card'),
  pattern: '{{9999}} {{9999}} {{9999}} {{9999}}',
  onPasteEvent: function (payload) {
    var value = payload.unformattedInputValue;

    if (requiresAmexPattern(value)) {
      formattedCreditCardInput.setPattern('{{9999}} {{999999}} {{99999}}')
    } else {
      formattedCreditCardInput.setPattern('{{9999}} {{9999}} {{9999}} {{9999}}')
    }
  })
});

API

options

KeyTypeDescription
elementHTMLInputElement or HTMLTextAreaElementA valid reference to an input or textarea DOM node
patternStringPattern describing the allowed character set you wish for entry into corresponding field. See Patterns.
onPasteEventFunction (optional)A callback function to inspect the unformatted value of the input during a paste event. See Paste Event.

Related