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. */
Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to Geekpedia.com. With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

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

Back To Top