Source Code: Credit card number validation (Israeli Visa)

Posted on Jan 18, 2010

Sometimes, you need more then the simple straight forward validation of a credit card number.

Usually, it’s enough, yet sometimes a client demand or a product demand is to create a more sophisticated validation, using known credit card algorithm that the CreditCard company issues from time to time.

I had just that need a while back.

So, I created the validation and I decided to share it with you here.

First, let’s create a helper for checking wether a number is an even or an odd number. this will be used later in the validation process.

A credit card validation is being done using something that’s called a “weight number”, each credit card number is attached to a weight number and some calculations are done accordingly. So, let’s create a class which takes a number and a weight number, we will also create a constructor for this class.

Now, we have the helper to check whether a number is odd or even, we have a class to hold the credit card numbers.

The algorithm says something simple, starting at the right side of the number (credit card number) start attaching weight numbers.

Start with 1, then 2 and so on and so fourth till the end of the number.

like so:

Numbers and weight numbers

After you do this, multiply the number with the weight number, if the result you get is greated then the number 10, add the first number to the second number.

Example: if you get 16 in the result, simply add 1+6 and the final result is 7.

like so:

Calculation metod - weight numbers

After you do this, simply sum up the result

8+5+7+0+2+4+0+0+0+1+4+1+6+2+2+8

Any result should is OK as long as the number is divided by 10, if the number is not divided by 10 exactly something is wrong with the credit card.

This is the final validation function

The function is commented so no further explanation is needed.

Feel free to ask any question in the comments