I while back I wrote a messy bit of JavaScript for handling credit cards and routing numbers on a web portal that allowed customers to pay their recurring bill online. It was efficient, but I cannot for the life of me find it. I wrote it at work and I suppose I didn’t think to save it.

Anywho… I decided to write a cfc. It is not finished by any means, but wanted to put it out here to see if anyone had any feedback. If you are new to CFC’s and don’t quite understand, I’ll be posting some more details in the future, but for now this would be for users comfortable with cfc’s.

Feedback welcomed and encouraged.

<cfcomponent>
<cffunction name="checkCreditCard" access="remote" returntype="string">
  <cfargument name="cardNumber" type="numeric" required="yes">

  <cfif left(arguments.cardNumber,1) eq 4>
    <cfset cardType = 'VISA'>
    <cfset totalDigits = 16>
  <cfelseif listFind('51,52,53,54,55',left(arguments.cardNumber,2))>
    <cfset cardType = 'MASTERCARD'>
    <cfset totalDigits = 16>
  <cfelseif listFind('34,37',left(arguments.cardNumber,2))>
    <cfset cardType = 'AMERICANEXPRESS'>
    <cfset totalDigits = 15>
  <cfelseif left(arguments.cardNumber,4) eq 6011>
    <cfset cardType = 'DISCOVER'>
    <cfset totalDigits = 16>
  </cfif>
<!---
MASTERCARD:51-55,  16
VISA:  4|13,  16
AMEX:  34|37,  15
Discover:  6011, 16
--->
  <cfset validCardTypes = "Visa, MasterCard, AmericanExpress, Discover">

  <cfif listFind('3,4,5,6',left(arguments.cardNumber,1)) eq 0>
    <cfset returnError = "This card type is not supported.  Please use one of the following:  #validCardTypes#">
  <cfelse>

    <cfif len(arguments.cardNumber) neq totalDigits>
      <cfset  errorMsg = 'The #cardType# that you entered in not valid.  Visa card numbers are #totalDigits# long and you entered a #len(arguments.cardNumber)# digit number.'>
    <cfelse>
      <cfset myCount = 0>
      <cfloop from="1" to="#totalDigits#" index="i">
        <cfif i mod 2 neq 0>
          <cfset  myCount = myCount + i>
        <cfelseif i mod 2 eq 0 and i neq 16>
          <cfset  tempNum = 2 * i>
          <cfif len(tempNum) eq 2>
            <cfset  tempNum = left(tempNum,1) + left(tempNum,2)>
          </cfif>
          <cfset  myCount = myCount + tempNum>
        </cfif>
      </cfloop>

    <cfif myCount mod 10 neq 0>
      <cfset  errorMsg = 'The #cardType# that you have entered is incorrect.  Please check the number and try again.'>
    </cfif>

  </cfif>  <!--- /if len(arguments.cardNumber) neq totalDigits --->
  </cfif>  <!--- /if listFind('3,4,5,6',left(arguments.cardType,1)) eq 0 --->

<cfreturn errorMsg>
</cffunction>
</cfcomponent>