Validating credit card numbers

This JavaScript function checks a text field for a valid credit card number through several validation methods.
  1. // This code validates a credit card number
  2. function ValidateCC(fieldToValidate)
  3. {
  4.  // Validate for numbers only
  5.  var ccRE=/\W/gi;
  6.  var CCnumber=fieldToValidate.value.replace(ccRE, "");
  7.  if(isNaN(CCnumber))
  8.  {
  9.  alert("Credit card number is not numeric.");
  10.                 fieldToValidate.focus();
  11.  return false;
  12.  }
  13.  // Validate for the number of digits in the credit card number
  14.  if((CCnumber.length!=16) && (CCnumber.length!=18))
  15.  {
  16.  alert("Incorrect number of digits in credit card number.");
  17.                 fieldToValidate.focus();
  18.  return false;
  19.  }
  20.  // More advanced validation using a mathematical formula that applies to all credit card numbers
  21.  var cardMath=0;
  22.  for (i=CCnumber.length; i>0; i--)
  23.  {
  24.  if (i % == 1)
  25.  {
  26.  var doubled = "" + (parseInt(CCnumber.substring(i - 1, i)) * 2);
  27.  if(doubled.length==2)
  28.  {
  29.                                 doubled = parseInt(doubled.substring(0,1)) + parseInt(doubled.substring(1,2))
  30.  }
  31.                         cardMath += parseInt(doubled);
  32.  }
  33.  else
  34.  {
  35.                         cardMath += parseInt(CCnumber.substring(i - 1, i))
  36.  }
  37.  }
  38.  if(cardMath % 10 != 0)
  39.  {
  40.  alert("Credit card number is invalid.");
  41.                 fieldToValidate.focus();
  42.  return false;
  43.  }
  44. }
  45. /*
  46. <form onSubmit="return ValidateCC(this.txtCC);">
  47. <input type="text" name="txtCC">
  48. <input type="submit" value="Validate">
  49. </form>
  50. */

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top