Last active
August 29, 2015 14:21
-
-
Save crueber/faad2648f6c4215eaf3f to your computer and use it in GitHub Desktop.
Credit Card Checksum (Luhn) validation in CoffeeScript w/ Angular Directive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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