C# Javascript - Developer Resourses - Validating Creditcard number ASP.NET C# with Javascript ::: Lionfish Tehcnologies



Home / Developers Resourses / Tips

Validating Creditcard number ASP.NET C# with Javascript.

Here is how I developed a validation of a credit card number on the client-side with javascript using Luhn algorithm.

///
/// Function called from Validator object to Validate a credit card number
///
function CCNumberValidation(oSrc, args)
{
   var ddCCTypeCtl = document.getElementById('');
   //alert(ddCCTypeCtl.value);
   if (IsCreditCardValid(ddCCTypeCtl.value))
      args.IsValid = true;
   else
      args.IsValid = false;
}

/// Validates a credit card number using the standard Luhn/mod10
/// validation algorithm.
/// /// Card number, with or without punctuation
/// Return True if card number appears valid, false if not
function IsCreditCardValid(cardNumber)
{
   var allowed = "0123456789";
   var i;
   var cleanNumber = new StringBuilder();
   var ceros = new StringBuilder();
   //alert("cardNumber:" + cardNumber);
   for (i = 0; i < cardNumber.length; i++)
   {
      if (allowed.indexOf(cardNumber.substring(i, i + 1)) >= 0)
         cleanNumber.Append(cardNumber.substring(i, i + 1 ));
   }
   //alert("CLEAR NUMBER:" + cleanNumber.ToString());
   if (cleanNumber.length <> 16)
      return false;
   for (i = cleanNumber.length + 1; i <= 16; i++)
      ceros.Append("0");
   var multiplier, digit, sum, total = 0;
   var number = ceros.ToString() + cleanNumber.ToString();
   //alert("FULL NUMBER:" + number);
   for (i = 1; i <= 16; i++)
   {
      multiplier = 1 + (i % 2);
      digit = parseInt(number.substring(i - 1, i));
      sum = digit * multiplier;
      if (sum > 9)
         sum -= 9;
      total += sum;
   }
   //alert("TOTAL:" + total);
   return (total % 10 == 0);
}


Here is the code on the page:


<div style="font-size: 16px; font-family: arial; white-space: pre; text-align: left">
   <tr>
      <td>Card Number:</td>
      <td>
         <asp:TextBox ID="txtCCNumber" runat="server"></asp:TextBox>
         <asp:RequiredFieldValidator ID="RequiredFieldValidator2"
            runat="server"
            ControlToValidate="txtCCNumber"
            ErrorMessage="Card Number is Required."
            ValidationGroup="payment"
            Display="None">
         </asp:RequiredFieldValidator>
         <asp:CustomValidator ID="custValidCCNumber"
            runat="server"
            ControlToValidate="txtCCNumber"
            ErrorMessage="Invalid Creditcard number"
            ClientValidationFunction="CCNumberValidation"
            ValidationGroup="payment"
            Display="Dynamic">Invalid Creditcard number</asp:CustomValidator>       </td>
   </tr>



Lionfish Technologies ® 2009 All rights reserved