Skip to content

Instantly share code, notes, and snippets.

@davesag
Created May 14, 2019 05:31
Show Gist options
  • Save davesag/5bee0c8c556e856d107bf0ffe7b4c565 to your computer and use it in GitHub Desktop.
Save davesag/5bee0c8c556e856d107bf0ffe7b4c565 to your computer and use it in GitHub Desktop.
Luhn Algorithm for Luhn validation of credit card number
const isValid = card => {
const value = card ? card.replace(/\D/g, "") : ''
if (!value) return false
let nCheck = 0
let bEven = false
for (let n = value.length - 1; n >= 0; n--) {
const cDigit = value.charAt(n)
let nDigit = parseInt(cDigit, 10)
if (bEven && (nDigit *= 2) > 9) nDigit -= 9
nCheck += nDigit
bEven = !bEven
}
return (nCheck % 10) === 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment