Validating and Formatting Credit Card Inputs with Payment.js

Category: Form , Javascript | June 14, 2018
Author:
Views Total: 2,591
Official Page: Go to website
Last Update: June 14, 2018
License: MIT

Preview:

Validating and Formatting Credit Card Inputs with Payment.js

Description:

Payment.js is a standalone Javascript library for E-commerce or business websites that helps you validate and format credit card form elements. Currently supports Visa, MasterCard, American Express, Discover, JCB, Diners Club, Maestro,Laser and UnionPay.

Features:

  • 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>
</form>

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');

Payment.restrictNumeric(numeric);
Payment.formatCardNumber(number);
Payment.formatCardExpiry(exp);
Payment.formatCardCVC(cvc);

document.querySelector('form').onsubmit = function(e) {
  e.preventDefault();
  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');
  }
}

Changelog:

v2.3.0 (06/14/2018)

  • Update

Leave a Reply