The following is a Javascript credit card number validator and formatter. We use this code to assist our customers by ensuring that they at least type in a credit card number with the correct format and checksum.
This code is intended to be used to improve the user experience by avoiding submitting mistakes in a credit card number. Naturally the cgi will have to submit the data to your credit card processor or bank to ensure that the card has been issued, not recinded and has available funds.
An example of its use follows:
<form> <input type="text" name="Card #" onChange='checkCC()' size=20> </form>
The following code should be included in the document header
<script type=text/javascript> function checkCC(){ var ccnum = document.forms[0].elements["Card #"].value; var month = 0; var year = 0; var checksum = 0; var factor = 0; // do checksum validation on credit card number and // reformat so it is easy to read by a human ccnum = ccnum.replace(/[^0-9]/gi,""); if(ccnum.length < 16) { alert("Please enter a valid credit card number"); document.forms[0].elements["Card #"].focus(); return false; } if(ccnum.length %2 ) { factor = 1; } else { factor = 2; } for(x=0; x< ccnum.length; x++) { digit = ccnum.charAt(x); if(digit * factor > 9) { checksum += (digit * factor) - 9; } else { checksum += digit * factor; } factor = (factor%2)+1; } // reformat with hyphens every 4 chars document.forms[0].elements["Card #"].value = ccnum.replace(/([0-9]{0,4})([0-9]{0,4})([0-9]{0,4})([0-9]{0,4})/, "$1-$2-$3-$4"); if(checksum % 10) { alert("The card number you entered is not valid.\n"+ "Please try again..."); document.forms[0].elements["Card #"].focus(); return false; } // VISA is 4xxx xxxx xxxx xxxx // MC is 5{0-5}xx xxxx xxxx xxxx // BC is 56xx xxxx xxxx xxxx if ((ccnum.charAt(0)) == 4 || (ccnum.charAt(0)) == 5) { return true; } else { alert("We only accept VISA, Mastercard and Bankcard.\n"+ "Please use one of these cards to pay your account."); document.forms[0].elements["Card #"].focus(); return false; } return true; } </script>