This is the Bocoup web log with posts from Al, Ben, Boaz, Darius, Greg, Irene, John, Mike, Nate, Nick, Pete, Richard, Rick, Sam, Sam Clearman, Scott and Tim. You should also make sure to checkout code.bocoup.com, where we keep the finished versions of ideas we kick around here.



Feb 22, 2010

JavaScript Credit Card Validation

I was reading 2600 on the bus recently and came across a credit generation algorithms which got me thinking… if you are building a web application that charges credit cards, at which point would card validation make most sense? I came to the conclusion that an efficient system, would check the credit card number was valid on the client side. This way there is little-to-no network traffic containing invalid card numbers.

Checking credit card numbers is actually pretty simple. Most services will use something called a Luhn Check, which multiplies odd indices by two, sums their digits and then divides the total sum by ten. If the result of the sum % 10 == 0 then the card number is ‘likely’ to be valid.

I came up with a a short function to validate credit card numbers passed as Strings or Floats.

  var cardValid = function( cardNo ){    
    var sum = 0, iNum;
    for( var i in cardNo+='' ){
      iNum = parseInt(cardNo[i]);
      sum += i%2?iNum:iNum>4?iNum*2%10+1:iNum*2;
    }
    return !(sum%10);
  };

To use this function, just call cardValid( cardNo ) which will return either true or false.




Comments:




Please send your questions to this address or call Bocoup at 617-379-2752.
This web page is proudly maintained by Bocoup and hosted by (mt) Media Temple.
All code on this website is Open Source. Want to work at Bocoup? Then Apply.
HTML5 Powered with Connectivity / Realtime, CSS3 / Styling, Device Access, Graphics, 3D & Effects, Multimedia, Performance & Integration, Semantics, and Offline & Storage