Validating and Formatting Credit Card Inputs with Payment.js

Category: Form , Javascript , Recommended | June 12, 2021
Views Total:5,807 views
Official Page:Go to website
Last Update:June 12, 2021


Validating and Formatting Credit Card Inputs with Payment.js


Payment.js is a standalone Javascript library for E-commerce or business websites that help you validate and format credit card form elements.

Currently supports Visa, MasterCard, American Express, Discover, JCB, Diners Club, Maestro, Laser, ELO, MIR, Troy, Maestro,  and UnionPay.


  • Card number formatting
  • Expiry formatting
  • CVC formatting
  • Restrict Numeric
  • Validate inputs while submitting.

How to use it:

Load the payment.js in your Html document.

<script src="lib/payment.js"></script>

Create a credit card form.

<form novalidate autocomplete="on">
  <h2>Card number formatting</h2>
  <input type="text" class="cc-number" pattern="\d*" x-autocompletetype="cc-number" placeholder="Card number" required>
  <h2>Expiry formatting</h2>
  <input type="text" class="cc-exp" pattern="\d*" x-autocompletetype="cc-exp" placeholder="Expires MM/YY" required maxlength="9">
  <h2>CVC formatting</h2>
  <input type="text" class="cc-cvc" pattern="\d*" x-autocompletetype="cc-csc" placeholder="Security code" required  autocomplete="off">
  <h2>Restrict Numeric</h2>
  <input type="text" data-numeric>
  <h2 class="validation"></h2>
  <button type="submit">Submit</button>

The Javascript to enable the validation.

var J = Payment.J,
  numeric = document.querySelector('[data-numeric]'),
  number = document.querySelector('.cc-number'),
  exp = document.querySelector('.cc-exp'),
  cvc = document.querySelector('.cc-cvc'),
  validation = document.querySelector('.validation');
document.querySelector('form').onsubmit = function(e) {
  J.toggleClass(document.querySelectorAll('input'), 'invalid');
  J.removeClass(validation, 'passed failed');
  var cardType = Payment.fns.cardType(J.val(number));
  J.toggleClass(number, 'invalid', !Payment.fns.validateCardNumber(J.val(number)));
  J.toggleClass(exp, 'invalid', !Payment.fns.validateCardExpiry(Payment.cardExpiryVal(exp)));
  J.toggleClass(cvc, 'invalid', !Payment.fns.validateCardCVC(J.val(cvc), cardType));
  if (document.querySelectorAll('.invalid').length) {
    J.addClass(validation, 'failed');
  } else {
    J.addClass(validation, 'passed');


v2.4.4 (06/12/2021)

  • Removed Visa 18 digit option
  • Browser AutoFill fix

v2.4.3 (04/02/2021)

  • Fix NPM

v2.4.2 (04/02/2021)

  • Fixed globalThis dependency

v2.4.1 (04/01/2021)

  • Fix: Use ‘input’ event for mobile browser
  • Fix: Maestro updates
  • Fix: add globalThis polyfill
  • Fix: JCB cards starting with “35” are JCB
  • Fix: Android expiry formatting
  • Fix: expiry not formatted on android

v2.4.0 (07/28/2020)

  • Adds detection for Maestro, Elo, Troy, Mir, and JCB

v2.3.0 (06/14/2018)

  • Update

You Might Be Interested In:

Leave a Reply