Credit Card Validation Plugin in Jquery

Introduction


It's been a long time since my last post. In the last two months I was running through a hectic schedule, so could not publish anything here.

But this time I am here with my first ever JQuery Plugin and that's on Credit Card Validation.

While working with any payment gateway its an important thing to validate the correct credit card/debit card details. You may have developed an interface where the user has to give the credit card details like card no, cvv no, expiry date, name on the card. These fields need to be validated before processing towards the payment.

In order to validate the credit card details you may use the jquery or server side coding with the help of regex expressions, which is a time taking thing. So I thought of developing an efficient plugin which can create a nice looking interface along with the user friendly validations that can be consumed in any type of application. So here it is.

In this post we will see how this plugin works and how to use it in your application. You can download the plugin from the below link.

   Download Source Code Here

  Let's Validate the Credit Card Details








**I have used bootstrap for design purpose, you can use it or not according to your project requirement.

Before entering into the plugin details lets know some basic things about the credit card number pattens.

The first digit in your credit-card number signifies the system:

    3 - travel/entertainment cards (such as American Express and Diners Club)
    4 - Visa
    5 - MasterCard
    6 - Discover Card

The structure of the card number varies by system. For example, American Express card numbers start with 37; Carte Blanche and Diners Club with 38.
  •  American Express - Digits three and four are type and currency, digits five through 11 are the account number, digits 12 through 14 are the card number within the account and digit 15 is a check digit.
  •  Visa - Digits two through six are the bank number, digits seven through 12 or seven through 15 are the account number and digit 13 or 16 is a check digit.
  • MasterCard - Digits two and three, two through four, two through five or two through six are the bank number (depending on whether digit two is a 1, 2, 3 or other). The digits after the bank number up through digit 15 are the account number, and digit 16 is a check digit.

(Courtesy: http://money.howstuffworks.com)

Lets get into the coding things. Ok first of all we will see the user interface and design it for enabling the user to provide his/her card details for validation and further proceedings.

I have used Bootstrap to get a UI like this, You can use it or else you can not according to your requirement.

This is how our UI is going to look like. Don't you guys like it ? please share your valuable comments below to modify it.
UI for CC Validation
Before we can start you need to download the plugin first. If you have not till now then download it from below.

Download Source Code

Once you download and extract it you will find the below javascript files in the js folder.
  • jquery-1.7.1.min.js
  • ccvalidate-tapan.min.js
We will be needing the ccvalidate-tapan.min.js file for our validation thing and you can add a latest JQuery to your project too.

 In the css folder you will find the below css files
  • bootstrap.css
  • Validation.css
Ok, Now lets jump into the coding part. Here is the HTML page how it looks like.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
    <link href="css/bootstrap.css" rel="stylesheet" />
    <link href="css/Validation.css" rel="stylesheet" />
    <script src="js/ccvalidate-tapan.min.js"></script>
    <script>
        $(document).ready(function () {
            // Initiate CC Validation
            InitiateValidation();

            // For check valid invalid details
            $("#btnValidate").click(function () {

                if (ValidateForm()) {
                    alert('You have entered valid details...');
                }
                else {
                    alert('You have entered invalid details/skipped some fields...');
                }
            });
        });

    </script>
</head>
<body>
    <div style="margin-top: 50px;" class="container">
        <div class="row">
            <div class="col-sm-5 col-xs-offset-3">
                <div class="well">

                    <div class="row">
                        <div class="col-sm-12">
                            <label class="col-sm-12 control-label">Enter Card No.</label>
                            <div class="col-sm-12">
                                <input placeholder="4587-7834-6735-1930" id="1" class="form-control" filtertype="CCNo">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-8">
                            <label class="col-sm-12 control-label">Expiry Date (MM/YY)</label>
                            <div class="col-sm-12">
                                <input placeholder="12/20" id="3" class="form-control" filtertype="Date">
                            </div>
                        </div>
                        <div class="col-sm-4">
                            <label class="col-sm-12 control-label pull-right">CVV</label>
                            <div class="col-sm-12">
                                <input placeholder="454" id="3" class="form-control" filtertype="Number">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-12">
                            <label class="col-sm-12 control-label">Name on Card</label>
                            <div class="col-sm-12">
                                <input placeholder="Tapan kumar" id="1" class="form-control" filtertype="CharacterAndSpace">
                            </div>
                        </div>
                    </div><br />
                    <div class="row">
                        <div class="col-sm-12">
                            <button id="btnValidate" class="btn btn-info col-sm-3 col-sm-offset-4 control-label">Submit</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

If you look into the above code you will find that I am using an attribute named filtertype for the input fields, which is responsible for the validation.

Here is the attribute values I have used for validating your card details.
  • Credit Card No : filtertype = "CCNo"
  • Expiry Date :  filtertype = "Date"
  • CVV No : filtertype = "Number"
  • Name on Card : filtertype = "CharacterAndSpace"

These attribute values are used into validate your card details and prevent user from inserting invalid entries in the input fields.
What you have to do is just to call 2 methods in JQuery in order to validate the card details. Find the script below.

<script>
        $(document).ready(function () {
            // Initiate CC Validation
            InitiateValidation();

            // For check valid invalid details
            $("#btnValidate").click(function () {

                if (ValidateForm()) {
                    alert('You have entered valid details...');
                }
                else {
                    alert('You have entered invalid details/skipped some fields...');
                }
            });
        });

    </script>

The  InitiateValidation() method initiates the validation, and ValidateForm() method will return a boolean if the form is valid or not and you can perform your task accordingly. Here I am showing some alert if the details are correct or not in the click event of the submit button.

That's all for your validation to work out.

Plugin Features :

  • while inserting the card no it will automatically put a "-" in between 4 digits.
  • It will not allow you put anything except numbers in the card input field.
  • It will show your card type at the right side of the text box.
  • Max length of the CCNo field is 19(including the "-").
  • In the Date field you wont be able to put anything except numbers and the field will not accept the first two digits greater than 12 as these two digits indicates the month.
  • Max length of the Expiry Date field is 6(including the "/").
  • Now the CVV no field will accept only 3 digits.
  • Finally the Name on Card field will accept a name, which should be at least of 3-4 characters.
Happy Coding...



8 comments:

  1. I really appreciate your work. Well done.

    ReplyDelete
  2. Hi Tapan,

    I've noticed in the expiry date field, when you input a forward slash '/' it enters as a double forward slash '//' instead. Is there a way to fix this?

    Cheers.

    ReplyDelete
    Replies
    1. Hi John,

      Thanks for your question. I have noticed this issue. and now modified a method in the js file. Here is the modified function. replace it with the existing one and it will work for you.

      function isDate(e, t) {
      e = e ? e : window.event;
      var n = e.which ? e.which : e.keyCode;
      var r = false;
      if (n >= 48 && n <= 57 || n == 8) {
      if (n == 8) {
      r = true
      } else if ($(t).val().length == 2) {
      var i = $(t).val();
      $(t).val(i + "/");
      r = true
      } else if ($(t).val().length == 5) r = false;
      else r = true;
      if ($(t).val().substring(0, 2) > 12) {
      r = false;
      $(t).val("")
      }
      } else {
      r = false
      }
      return r
      }

      What I am doing here is not allowing the user to enter the '/' instead the system will automatically put a '/' after first two digits.

      Thanks
      Tapan kumar

      Delete
  3. Nice code however you need to stop the user from entering any non numerics. Please take a look at this
    if ( String.fromCharCode( e.which ).match( /[0-9 -()+]+$/ ) )
    {
    if ( n >= 48 && n <= 57 || n == 8 )
    {
    if ( n == 8 ) { r = true }
    else if ( $( t ).val().length == 4 || $( t ).val().length == 9 || $( t ).val().length == 14 )
    {
    var i = $( t ).val(); $( t ).val( i + "-" );
    r = true
    }
    else if ( $( t ).val().length < 19 ) r = true;
    else r = false
    }
    else
    { r = false }
    if ( r ) { if ( isValid ) isValid = true }
    else { isValid = false; }
    }
    else
    { r = false; }
    return r

    ReplyDelete
    Replies
    1. Yes this can be used to prevent the user from entering non numeric values

      Delete
  4. Nice article. Thanks for sharing. you take a look at the example here for credit card data validation on client side in asp.net

    ReplyDelete