Forked from DiegoSalazar/validate_credit_card.js
Last active
February 1, 2018 16:42
-
-
Save dmitrye/9957704 to your computer and use it in GitHub Desktop.
JavaScript Luhn validator method. Modifications made here include support for non-numeric characters in the value being cleaned up instead of rejecting the value. Also, cleaned up a duplicate variable and added identity check at the end instead of equality check.
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
// takes the form field value and returns true on valid number | |
function valid_credit_card(value) { | |
// The Luhn Algorithm. It's so pretty. | |
var nCheck = 0, bEven = false; | |
//this will remove all non-numeric characters and validate against remaining code. | |
//therefore this now supports 4111-1111-1111-1111 patterns as an example | |
value = value.replace(/\D/g, ""); | |
for (var n = value.length - 1; n >= 0; n--) { | |
var cDigit = value.charAt(n), | |
nDigit = parseInt(cDigit, 10); | |
if (bEven) { | |
if ((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