Skip to content

Instantly share code, notes, and snippets.

@crueber
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crueber/faad2648f6c4215eaf3f to your computer and use it in GitHub Desktop.
Save crueber/faad2648f6c4215eaf3f to your computer and use it in GitHub Desktop.
Credit Card Checksum (Luhn) validation in CoffeeScript w/ Angular Directive
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
rootModule.directive 'isCardValid', ->
{
require: 'ngModel'
link: (scope, elm, attr, ctrl) ->
ctrl.$validators.text = (model, view) ->
is_valid_credit_card String(model)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment