Are you valid? - Task 3

Introduction

As it turns out validating a visa card is not that hard. All you need is to follow the Luhn algorithm. For this instalment of the series I used JavaScript to validate any Visa credit card number with simple mathematical calculations based off the work of Hans Peter Luhn.


Work

The obvious start to all web based validators is creating an html document that can handle the input from the user. In our case all we require is a simple text field as well as a submit button. For a successful completion of the task I was required to include four criteria in the JavaScript code.

  1. All Visa card numbers start with a 4.
  2. All Visa card numbers are between 13 and 16 digits.
  3. There can only be integers in a Visa card number.
  4. They can all be validated through the Luhn algorithm.

Using a set of conditional arguments I could quickly cross off the first three criteria in the list above. However the Luhn formula required some deeper thought process to solve. For those unfamiliar with the algorithm for Visa card numbers, these are the steps.

  1. Multiply each other digit from the right to the left with 2, skipping the rightmost.
  2. Retrieve the digit sum of the number calculated from step 1.
  3. To the sum add the remaining digits, skipping the rightmost.
  4. Validate the result by summing the total of the number and rightmost digit, followed by modulating by ten (%10).
  5. If the remainder is 0 the number is valid.

Using these instuctions I constructed three for loops; one for the multiplication, one for calculating the digit sum and finally one for summarizing the remaining digits with the results from the first two loops. Lastly returning a Boolean based on the final validation result.

Throughout the program the user is notified with alert dialogs explaining each mistake or if the validation process was successful.

Final result
Final result