Visual Basic Code of the Week (COTW)
http://www.codeoftheweek.com
Issue #118
Online Version at http://www.codeoftheweek.com/membersonly/bi/0118.html (paid subscribers only)
All content and source code is Copyright (c) 2000 by C&D Programming Corp. No part of this issue can be reprinted or distributed in any manner without express written permission of C&D Programming Corp.

Issue topic: Formatting credit card numbers (non-secure and secure)

Earn REAL money surfing the web!

If you would like to make some extra cash for surfing the web, jump to http://www.codeoftheweek.com/paidsurf.html

Requirements

In this Issue

In this issue we discuss how properly (at least in our opinion) format credit card numbers. This routine is useful for anyplace a credit card number is captured or displayed. It should work well in VBScript with very little modifications.

If you have any questions about using this module, let us know at questions@codeoftheweek.com

basCCFormat

This module contains a single routine called FormatCreditCardNumber that takes a string of digits and processes it to produce a nicely formatted credit card number.

Functions

Public Function FormatCreditCardNumber(sCardNumber As String, Optional bSecure As Boolean = False) As String

This function returns a formatted credit card number using separate formats for the different types of credit/charge cards. An American Express card is 15 digits and has the number grouped differently than Visa, MasterCard and Novus cards. The default number separator is a - (dash). If you want the return string to show a secure representation of the card number just set the bSecure option to True. This will cause this function to put X characters in the place of all numbers except the last four digits.

American Express numbers will be formatted as 1234-123456-12345. All others will be formatted as 1234-1234-1234-1234.

One really nice feature of this routine is that the input string specified by sCardNumber can be any format as long as it has 15 or 16 digits. For example, 1111-1111-2222-2222 or 11111111 222 2 2222 would result in the same output string. The routine "cleans" the string first by removing any non-numeric character and then reformats it according to the specific rules defined in this function. This is REALLY useful for those web sites that gather information from users that can enter numbers any way they wish.

Sample Usage

Some examples are shown using different credit card numbers (NOTE: the credit card numbers are not real card numbers).

    Debug.Print FormatCreditCardNumber("4234123412341234")
    ' will print out as 4234-1234-1234-1234
    Debug.Print FormatCreditCardNumber("4234123412341234",True)
    ' will print out as XXXX-XXXX-XXXX-1234
    Debug.Print FormatCreditCardNumber("323412341234123",True)
    ' will print out as XXXX-XXXXXX-X4123

Source Code

Create a new module and paste this code into it. Call the module basCCFormat.

If you have any questions, email us at help@codeoftheweek.com

'----------------------------------------------------------------------
'
'   Module Name:    basCCFormat
'   Written By:     C&D Programming Corp.
'   Create Date:    1/2000
'   Copyright:      Copyright 2000 by C&D Programming Corp.  Source
'                   code may not be reproduced except for use in a
'                   compiled executable.  All rights reserved.  If
'                   you would like to reprint any or all of this
'                   code please email us at info@codeoftheweek.com
'
'----------------------------------------------------------------------

Option Explicit
Private Const CARD_DELIM = "-"

Private Function StripAllButNumbers(sData As String) As String
    Dim sTemp As String
    Dim x As Long
    Dim sCh As String

    ' scan through the string and add all the numeric characters to
    ' temporary string.
    sTemp = ""
    For x = 1 To Len(sData)
        sCh = Mid$(sData, x, 1)
        If sCh >= "0" And sCh <= "9" Then
            sTemp = sTemp & sCh
        End If
    Next
    StripAllButNumbers = sTemp
End Function

Public Function FormatCreditCardNumber(sCardNumber As String, Optional bSecure As Boolean = False) As String
    Dim sTempCard As String
    Dim sFormattedCard As String

    sFormattedCard = "" ' let's assume the number is invalid for now.

    ' first make sure we are dealing with a clean credit card number, no spaces
    ' dashes or anything else
    sTempCard = StripAllButNumbers(sCardNumber)

    ' american express is 15 digits; visa,mastercard,novus is 16 digits
    ' if anyone has any other cards let us know and we can add them here
    If Len(sTempCard) = 15 Or Len(sTempCard) = 16 Then
        ' card number is the right length so let's format it appropriately.
        Select Case Left(sTempCard, 1)
            Case "3" ' 3=amex
                If Len(sTempCard) <> 15 Then
                    Err.Raise 5, "FormatCreditCardNumber", "An American Express card number must be 15 characters long"
                End If
                If bSecure Then
                    sFormattedCard = "XXXX" & CARD_DELIM & "XXXXXX" & CARD_DELIM & _
                                        Right(sTempCard, 5)
                Else
                    sFormattedCard = Left(sTempCard, 4) & _
                                CARD_DELIM & Mid(sTempCard, 5, 6) & _
                                CARD_DELIM & Right(sTempCard, 5)
                End If
            Case "4", "5", "6"  ' 5=mc,4=visa,6=discover
                If Len(sTempCard) <> 16 Then
                    Err.Raise 5, "FormatCreditCardNumber", "A Visa, MasterCard or Novus card number must be 16 characters long"
                End If
                If bSecure Then
                    sFormattedCard = "XXXX" & CARD_DELIM & "XXXX" & CARD_DELIM & _
                                        "XXXX" & CARD_DELIM & Right(sTempCard, 4)
                Else
                    sFormattedCard = Left(sTempCard, 4) & _
                                CARD_DELIM & Mid(sTempCard, 5, 4) & _
                                CARD_DELIM & Mid(sTempCard, 9, 4) & _
                                CARD_DELIM & Right(sTempCard, 4)
                End If
            Case Else
                ' not sure exactly what to do if the card does not match one of the above
                ' types.  Feel free to adjust as desired.
                If bSecure Then
                    sFormattedCard = String(Len(sTempCard) - 4, "X") & _
                                        Right(sTempCard, 4)
                Else
                    sFormattedCard = sTempCard
                End If
        End Select
    Else
        Err.Raise 5, "FormatCreditCardNumber", "The card number you supplied is not valid.  It must be either 15 or 16 characters long."
    End If
    FormatCreditCardNumber = sFormattedCard
End Function

This document is available on the web

Paid subscribers can view this issue in HTML format. There is no additional source or information in the HTML formatted document. It just looks a little better since we have included some HTML formatting. Just point your browser to link at the top of this document.

Get paid to surf the web!

If you would like to get paid for surfing the web, jump to http://www.codeoftheweek.com/paidsurf.html

Other links

Contact Information

C&D Programming Corp.
PO Box 20128
Floral Park, NY 11002-0128
Phone or Fax: (212) 504-7945
Email: info@codeoftheweek.com
Web: http://www.codeoftheweek.com