Created
May 2, 2014 06:28
-
-
Save ecoologic/5774b50422ef34cecd92 to your computer and use it in GitHub Desktop.
credit card validation
This file contains hidden or 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
cardType = (cc) -> | |
result = "unknown" | |
result = "mastercard" if /^5[1-5]/.test(cc) | |
result = "visa" if /^4/.test(cc) | |
result = "amex" if /^3[47]/.test(cc) | |
result | |
luhn = (cc) -> | |
sum = 0 | |
alt = false | |
for i in [cc.length - 1..0] by -1 | |
# Get the next digit. | |
num = parseInt cc.charAt(i), 10 | |
# If it is not a valid number, abort. | |
return false if isNaN(num) | |
# If it is an alternate number... | |
if alt | |
num *= 2 | |
num = (num % 10) + 1 if num > 9 | |
# Flip the alternate bit. | |
alt = !alt | |
# Add to the rest of the sum. | |
sum += num | |
# Determine if it is valid. | |
sum % 10 is 0 | |
$ -> | |
$('form.credit-card #number').change (ev) -> | |
cc = $(@).val() | |
type = cardType(cc) | |
validity = if luhn(cc) then "Valid" else "Invalid" | |
$('form.credit-card .credit-card-type').html(type) | |
$('form.credit-card .valid-credit-card').html(validity) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment