Press "Enter" to skip to content

[Payment] Creating Credit Card Forms, Validating Inputs, and Formatting Numbers

Payment is a free general-purpose library of jQuery for building credit card forms, input validation, and number formatting. Largely based on jquery.payment @stripe library, but without jQuery.

Payment.js is a standalone javascript library for eCommerce or business sites that helps you validate and format elements of a credit card form.

Supported card types are:

  • Visa
  • MasterCard
  • American Express
  • Discover
  • JCB
  • Diners Club
  • Maestro
  • Laser
  • UnionPay
  • Elo
  • Hipercard
  • Troy

How to make use of it:

Load the payment.js in your Html doc.

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

Validating and Formatting Credit Card Inputs, Payment Plugin/Github


See Demo And Download

Official Website(jessepollak): Click Here

This superior jQuery/javascript plugin is developed by jessepollak. For extra Advanced Usages, please go to the official website.

Be First to Comment

    Leave a Reply

    Your email address will not be published. Required fields are marked *