Validate Credit Card Number

Uncle Pete’s Freebie of the day…..

I need to validate the credit card number a user enters, so after some Googleing I came up with this function. It accepts the credit card number as a string then strips any spaces or dashes off. It then performs a few test to determine the card type, and check sum. If it determines that the number is a valid credit card number then it returns the card type, otherwise it returns an empty string.

Enjoy!

PROCEDURE ValidateCCNumber(LOCAL CardNumber is string)

CardType is string
TotalSum is int
CardNumber = Replace(CardNumber,"-","")
CardNumber = Replace(CardNumber," ","")

IF Val(Middle(CardNumber, 1, 2)) >= 51 AND Val(Middle(CardNumber, 1, 2)) <= 55 AND Length(NoSpace(CardNumber)) = 16 THEN
 CardType = "Master Card"
END
IF Val(Middle(CardNumber, 1, 1)) = 4 AND ( Length(NoSpace(CardNumber)) = 13 OR Length(NoSpace(CardNumber)) = 16) THEN
 CardType = "Visa"
END
IF (Val(Middle(CardNumber, 1, 2)) = 34 OR Val(Middle(CardNumber, 1, 2)) = 37) AND Length(NoSpace(CardNumber)) = 15 THEN
 CardType = "American Express"
END 
IF Val(Middle(CardNumber, 1, 4)) = 6011 AND Length(NoSpace(CardNumber)) = 16 THEN
 CardType = "Discover"
END 
IF CardType = "" THEN
 RESULT ""
END

FOR I = 1 _TO_ Length(NoSpace(CardNumber))
 SWITCH I
 CASE 1,3,5,7,9,11,13,15
 TotalSum = TotalSum + Val(Middle(CardNumber,Length(NoSpace(CardNumber)) - (I-1),1)) 
 OTHER CASE
 IF (Val(Middle(CardNumber,Length(NoSpace(CardNumber)) - (I-1),1))*2) > 9 THEN
 TotalSum = TotalSum + Val(Middle(NumToString((Val(Middle(CardNumber, Length(NoSpace(CardNumber)) - (I-1),1))*2),"2.0f"),1,1)) + Val(Middle(NumToString((Val(Middle(CardNumber, Length(NoSpace(CardNumber)) - (I-1),1))*2),"2.0f"),2,1))
 ELSE
 TotalSum = TotalSum + (Val(Middle(CardNumber,Length(NoSpace(CardNumber)) - (I-1),1))*2)
 END
 END
END

IF TotalSum modulo 10 <> 0 THEN
 RESULT ""
END

RESULT CardType

Now, back to your regular schedule program….

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s