Add

Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

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

  Behind The Scene








**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...



How To Call A JavaScript Method From C#

Introduction

This is very silly thing but used very often. Calling a JavaScript Method to do something from code behind(C#) is not so difficult.

You may need this thing in order to show a custom alert using jQuery modal pop up, or for custom redirection when you are in an IFrame.

Behind The Scene


Recently I was stuck in some redirection problems. The senario is something like, I was in some iframe but after session out I need to go back to the login page. But the control in not in my hand as I am inside an iframe.
I tried a lot of things but what resulted me is reloading or rendering the page I was referring inside the iframe. But my purpose was to redirect the whole page to login page.
So I did this using JavaScript, and I need to call a JavaScript function form the C# code when session is out.
There are some way in which you can call a JavaScript function from code behind.

  // redirect user to home page.
  ScriptManager.RegisterStartupScript(this, GetType(), "load", "closeDocumentIFrame();", true);
 
*closeDocumentIFrame(); is the method written in the aspx page
  // redirect user to home page.
  ClientScript.RegisterStartupScript(GetType(), "Load", String.Format("<script type='text/javascript'>closeDocumentIFrame();</script>"));
 
*closeDocumentIFrame(); is the method written in the aspx page
  // redirect user to home page.
  ClientScript.RegisterStartupScript(GetType(), "Load", String.Format("<script type='text/javascript'>window.parent.location.href ='{0}' </script>", "http://www.google.com"));
 
You can too add the JavaScript code here instead of writing another method in page level.

Happy Coding...

How To Check If Your Browser Supports HTML5 Or Not

Introduction


Recently while working on a video file integration in a website I got this interesting thing for you. As HTML5 supports your .mp4 video files and many more video files like .flv, .oog etc. But the main thing you need to sure about before integrating a video file is if your browser supports HTML5 or not.

If your browser does not support HTML5 then you can not play a .mp4 format in your website, so all you need is a flash video.

 

Behind The Scene


So my requirement was something like, I was asked to serve the user a flash video if his/her browser does not support HTML5 and .mp4 video if supports HTML5.

As you all of you know that there are many versions of IE till now those people are using, does not support HTML5. So this requirement is a genuine issue for all of us who are trying to integrate video files to their websites.

Let me clarify you if you have a HTML5 compatible browser then you just need 3 line of code to embed a .mp4 video to it in order to play it. See it below.
 <video width="320" height="240" controls>
 <source src="VideoFiles/movie.mp4" type="video/mp4">
  </video> 
Just put the above code to play a .mp4 file stored in the folder VideoFiles.

Now lets check for our main aim i.e HMTL5  compatibility.

Let's take a div inside your HTML code that contains both the .mp4 files and .swf files. Our main aim will be to hide one of them accordingly by considering the browser compatibility.
 <div>
 <object id="flashVideo" width="0" height="0" style="padding: 10px;">
     <embed width="320" height="240" src="videos/ansupalake.swf" style="margin-top: 10px;">
  </object>
   
 <video id="mp4Video"" width="320" height="240" controls>
      <source src="videos/ansupalake.mp4" type="video/mp4">
 </video> 
 </div>
 Now lets check in JavaScript regarding the compatibility.

 <script type="text/javascript">

    // Define the get_mime function
    var get_mime = function(filetype){
    var mimetype = '';
    var media_container = 'video';

    switch(filetype){
     case 'mp4':
      mimetype = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
      break;
     case 'ogg':
      mimetype = 'video/ogg; codecs="theora, vorbis"';
      break;
     case 'webm':
      mimetype = 'video/webm; codecs="vp8, vorbis"';
      break;
     case 'mp3':
      mimetype = 'audio/mpeg';
      media_container = 'audio';
      break;
    }
    
    return {'mimetype':mimetype,'container':media_container};  
    };

    // Check to see if the browser can render the file type
    // using HTML5
    var supports_media = function(mimetype, container) {
    var elem = document.createElement(container);
    
    if(typeof elem.canPlayType == 'function'){
     var playable = elem.canPlayType(mimetype);
     if((playable.toLowerCase() == 'maybe')||(playable.toLowerCase() == 'probably')){
      return true;
     }
    }
    return false;
    };

    // When the DOM has loaded check the file extension of each media link
    // and serve up appropriate media player
    $(document).ready(function(){
    
        /* Use the below three line to get the extension of a file dynamically. Here It gets the attribute "href" of a hyperlink
         and then extension            
          var path = $('#videoFile').attr('href');
          var extension = path.substring(path.lastIndexOf('.') + 1);
          var extension_info = get_mime(extension);
        */
    
        // Now get the MIME type for type mp4 files.
        var extension_info = get_mime('mp4');
    
        if(supports_media(extension_info.mimetype, extension_info.container))
                  {  
                    // Serve up an HTML5 Media Player and controls
                    serve_html5();
                  }
                  else
                  {
              // Serve up a flash based video for browsers that.
              serve_flash();
           } 
          });    

    function serve_flash(){
    $('#mp4Video').hide();
    }
    
    function serve_html5(){
    $('#flashVideo').hide();
    }
    
</script>
Let me explain what I have done in the above code. First in the document.ready function I am trying to get the MIME type of the video you want to play. ( here I am using a hard coded value .mp4, you can use the commented code to get the file extension from the HTML element dynamically )

OK, after getting the MIME type we are calling the supports_media method to check if it can create a video element in the DOM dynamically or not.

If it was able to create then we are sure that your browser supports HTML5 otherwise not. And exactly my code serves this way. It returns True if element was created successfully else returns you False . And then server you Flash or HTML5 accordingly by hiding the elements we have created before inside the div first.

Hope this article will help you to check if your browser supports HTML5 or not and to serve video files accordingly.

Happy Coding...

How To Change The Src Attribute Of An Image Tag In Jquery

Introduction


While walking through web design, you may wonder for sometime that how to change the a image source on clicking on it. It is a basic requirement when there is something you want to hide on clicking the image, and to unhidden by clicking on it again.

Let me explain this in a simple way;
There is a div which has a "+" image and another div below it. Our goal is to show that div when we click on the "+" image and to change the image from "+" to  "-". 
Again  when we click on the "-" image then the div will be hidden with the image changed from  "-" to "+".
Now I think the requirement is clear. Lets acheive this with Jquery.

Here is a screen shot how it will look like
Image On Off
   Download Source Code Here
   

Behind The Scene


Lets take a div with class headerList and an image tag inside it like below
        <div class="headerList">
            <img src="image/PLUS.gif" alt="xyz" class="ImageOnOff" style="cursor: pointer" />
            Header Section 1
        </div>
        <div class="childGrd">
            Body Part 1
        </div>

        <div class="headerList">
            <img src="image/PLUS.gif" alt="xyz" class="ImageOnOff" style="cursor: pointer" />
            Header Section 2
        </div>
        <div class="childGrd">
            Body Part 2
        </div>
From the above design you can see that there are two identical divs those have the same structure. And this will look like below.
Now, you can predict what I want to show you here. Yes I am going to click the "+" sign and that will open the slightly green div ( shown in the top screen shot ). Along with the showing the div the "+" sign will be converted to "-".

To acheive this you need to put the below JQuery code in your page.
<script type="text/javascript">

  $(function () {
   //Hide the green divs initially
   var id =  $(".headerList").closest('div');
   $(id).next('div.childGrd').hide();
    });
    // Change the image source when the image is clicked
    $("img.ImageOnOff").live('click', function () {
    
   if ($(this).attr("src").toString().indexOf('PLUS.gif') != -1) 
     {
    this.src = this.src.replace("PLUS.gif", "MINUS.gif");
     }
     else 
     {
    this.src = this.src.replace("MINUS.gif", "PLUS.gif");
     }
   
   // Toggle the green div when the image is clicked
   var currentRow = $(this).closest('div');
   var tr = $(currentRow).next('div');
   $(tr).toggle();
  }); 
 
 </script>
The above jquery code explains how to replace the image source on the click of the image and how to find the next div which has to be hidden.

Happy Coding...

How To Check Browser In JavaScript

Introduction


Its a very common thing as we know, how to check browser in Jquery. But he point is when we are going to do this in Javascript we will find a bit problem there as there is no inbuilt method to get you the exact browser. Here I will explain how to achieve this and what is the advantage of using Javascript instead of Jquery.



Behind The Scene


First lets focus why should we go for using Javascript instead of using Jquery where as its very simple to use the latter.

The point is that while using the Jquery you need to load the manifest file for each and every time you load the page. That is the "$" will need the jquery file so the browser downloads the whole file every time by reducing the performance of the site. Hence its always advisable that try avoiding Jquery when the work can be done through Javascript.

Recently I have a requirement of checking the browser so I did this in Jquery but when I go to my deployment manager to deployment manager for deploying this he denied me by telling me that for this small thing we don't need to load the whole Jquery manifest file. And advice me to do it in Javascript. Finally I got a way to do this in Javascript.

Javascript provides a object called "navigator" that gives the visitors browser's information.

The information from the navigator object can often be misleading, and should not be used to detect browser versions because:
  •     The navigator data can be changed by the browser owner
  •     Some browsers misidentify themselves to bypass site tests
  •     Browsers cannot report new operating systems, released later than the browser

Here is the code you can use this to check in cross browser, I have found this is giving the browser appCodeName "Mozila" in all my browsers and some different values. I mean if you want to check the browser name only you can not do this by using a particular object.

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    
</head>
<body>
<div id="example"></div>

<script>

txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
txt+= "<p>User-agent language: " + navigator.systemLanguage + "</p>";

document.getElementById("example").innerHTML=txt;

</script>
</body>
</html>
Here I found a way to do this in javascript. And below is the code for that
var BrowserDetect = {
 init: function () {
  this.browser = this.searchString(this.dataBrowser) ||
                                                       "An unknown browser";
  this.version = this.searchVersion(navigator.userAgent)
   || this.searchVersion(navigator.appVersion)
   || "an unknown version";
  this.OS = this.searchString(this.dataOS) || "an unknown OS";
 },
 searchString: function (data) {
  for (var i=0;i<data.length;i++) {
   var dataString = data[i].string;
   var dataProp = data[i].prop;
   this.versionSearchString = data[i].versionSearch ||
                                                             data[i].identity;
   if (dataString) {
    if (dataString.indexOf(data[i].subString) != -1)
     return data[i].identity;
   }
   else if (dataProp)
    return data[i].identity;
  }
 },
 searchVersion: function (dataString) {
  var index = dataString.indexOf(this.versionSearchString);
  if (index == -1) return;
  return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
 },
 dataBrowser: [
  {
   string: navigator.userAgent,
   subString: "Chrome",
   identity: "Chrome"
  },
  {  string: navigator.userAgent,
   subString: "OmniWeb",
   versionSearch: "OmniWeb/",
   identity: "OmniWeb"
  },
  {
   string: navigator.vendor,
   subString: "Apple",
   identity: "Safari",
   versionSearch: "Version"
  },
  {
   prop: window.opera,
   identity: "Opera",
   versionSearch: "Version"
  },
  {
   string: navigator.vendor,
   subString: "iCab",
   identity: "iCab"
  },
  {
   string: navigator.vendor,
   subString: "KDE",
   identity: "Konqueror"
  },
  {
   string: navigator.userAgent,
   subString: "Firefox",
   identity: "Firefox"
  },
  {
   string: navigator.vendor,
   subString: "Camino",
   identity: "Camino"
  },
  {  // for newer Netscapes (6+)
   string: navigator.userAgent,
   subString: "Netscape",
   identity: "Netscape"
  },
  {
   string: navigator.userAgent,
   subString: "MSIE",
   identity: "Explorer",
   versionSearch: "MSIE"
  },
  {
   string: navigator.userAgent,
   subString: "Gecko",
   identity: "Mozilla",
   versionSearch: "rv"
  },
  {   // for older Netscapes (4-)
   string: navigator.userAgent,
   subString: "Mozilla",
   identity: "Netscape",
   versionSearch: "Mozilla"
  }
 ],
 dataOS : [
  {
   string: navigator.platform,
   subString: "Win",
   identity: "Windows"
  },
  {
   string: navigator.platform,
   subString: "Mac",
   identity: "Mac"
  },
  {
      string: navigator.userAgent,
      subString: "iPhone",
      identity: "iPhone/iPod"
     },
  {
   string: navigator.platform,
   subString: "Linux",
   identity: "Linux"
  }
 ]

};
BrowserDetect.init();

Use this method in your page and it will return you the browser name by calling "BrowserDetect.browser" object.

You can download the sample code and check this by opening it on different browsers it will show you an alert containing the browser name, that you are using.

Happy Coding...

Create Cookie in Javascript

Introductions 


In this article I will show you how to create a cookie in JavaScript. Its very simple and you may need this for various purposes. I came across a problem where I need to solve the problem using cookie so I have tried this one.


Behind The Scene 


First of all you have to create a .html page ( you can do this in .aspx page ) also. But here in the example I will be showing you this through a html page.

Now take a button in the HTML page and call a JavaScript function"checkCookie()" on its onclick function.
 <input type="button" value="Click Me" onclick="checkCookie()" /> 
 Now go to the head section and define the  checkCookie() method there.
 function checkCookie() {
        var username = getCookie("username");
        if (username != null && username != "") {
            alert("Welcome again " + username);
        }
        else {
            username = prompt("Please enter your name:", "");
            if (username != null && username != "") {
                setCookie("username", username, 365);
            }
        }
    }
Here we are checking if the cookie named "username" exists or not. if exists then show an alert with the cookie name and if not then show a prompt where you can add the name in the textbox and that will be stored in cookie.

For geting the cookie it calls the getCookie() method.
 var username = getCookie("username");
Let's define the  getCookie() method.
 
function getCookie(c_name) {
        var c_value = document.cookie;
        var c_start = c_value.indexOf(" " + c_name + "=");
        if (c_start == -1) {
            c_start = c_value.indexOf(c_name + "=");
        }
        if (c_start == -1) {
            c_value = null;
        }
        else {
            c_start = c_value.indexOf("=", c_start) + 1;
            var c_end = c_value.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = c_value.length;
            }
            c_value = unescape(c_value.substring(c_start, c_end));
        }
        return c_value;
    }
 
In this method we are checking if the cookie named username exists or not if yes the return the value.

Now if not exists then we are calling the setCookie()  method bellow for setting the cookie value.

Here we are calling the "setCookie()"  method. whic takes 3 parameters the cookie name its value from the textbox and the time period upto which the cookie will be active.
setCookie("username", username, 365);
Now define the setCookie() method.
 
function setCookie(c_name, value, exdays) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + exdays);
        var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" 
                                          + exdate.toUTCString());
        document.cookie = c_name + "=" + c_value;
    }
 
Now you are done with the coding part just go and open the html page in the browser and see what happens.

Happy Codding...