crueber
5/21/2015 - 3:15 PM

Credit Card Checksum (Luhn) validation in CoffeeScript w/ Angular Directive

Credit Card Checksum (Luhn) validation in CoffeeScript w/ Angular Directive

rootModule.directive 'isCardValid', ->
  {
    require: 'ngModel'
    link: (scope, elm, attr, ctrl) ->
      ctrl.$validators.text = (model, view) ->
        is_valid_credit_card String(model)
  }
trim_the_fat = (str) -> str.replace(/\D+/g, '')
numerals_only = /[^0-9]+/
double_sum_array = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]

is_valid_credit_card = (card_number) ->
  card_number = trim_the_fat(card_number)
  return false if card_number.length < 13 or numerals_only.test(card_number)

  len = card_number.length
  sum = 0
  bit = 1

  while len
    digit = parseInt(card_number.charAt(--len), 10)
    sum += if (bit ^= 1) then double_sum_array[digit] else digit
  
  sum % 10 is 0