Validate a credit card number in JavaScript
12 August 2007 - JavaScript
When you're writing web apps, it's good to do validation both in the browser and on the server side. Do it in the browser to provide your user with instant feedback, and on the server for real security, as all client-side validation can be tricked or circumvented by those who know how.
Validating credit card numbers is a little tricky. They all follow a special algorithm, whose name I forget. But here are the mechanics of it...
- Reverse all the digits in the card number, as it if it a string
- Double the valid of every other digit, starting from the right, and concatenate with the unaffected digits
- Calculate the sum of all the digits in the new string
- If the original number was valid, the result should be exactly divisible by 10
/**
* Returns true if the string is a valid credit card number.
*
* @return bool
*/
String.prototype.is_valid_card_number = function()
{
// replace any white space in the card number
var number = this.replace(/\s+/g, '') ;
//replace if contains non-numbers
if(number.match(/\D/)){
return false ;
}
// convert to array and reverse the number
number = number.split('').reverse().join('') ;
// loop through the number one digit at a time
// double the value of every second digit starting
// from the right, and concatenate the new values
// with the unaffected digits
var digits = '';
for(var i = 0; i < number.length; i++){
digits += '' + ((i%2) ?
number.charAt(i) * 2 :
number.charAt(i)) ;
}
// add all of the single digits together
var sum = 0 ;
for (var i = 0; i < digits.length; i++){
sum += (digits.charAt(i) * 1) ;
}
//alert(sum) ;
// valid card numbers will be transformed into
// a multiple of 10
return (sum % 10) ? false : true ;
}
This function defines the validator as a method of String. So to use it, you can just call:
var valid = card_number.is_valid_card_number() ;Nice, huh?
if(valid){
alert('Good') ;
} else {
alert('Bad') ;
}


Comments
Credit Card Repair - 12 August 2007 15:57 - Visit >
[...] post by Nick Nettleton and software by ElliottBack [...]
Alan Hogan - 09 January 2008 21:28 - Visit >
Typo: "Double the valid of every other digit" => "Double the VALUE of every other digit"
Nice. Thanks for sharing, and thanks for parsing out hyphens and whitespaces from the credit card value. I HATE when sites disallow or require hyphens or spaces, or make you use for separate boxes and don't allow you to go back and fix a mistake....
Anyway, for anyone out there, REGEXP/smart parsing helps you help your customers!