LUHN Algorithm
The LUHN algorithm is a popular way to validate credit card numbers. I’ve used it many times while developing e-commerce applications to check that a user has entered their credit card number correctly. By using the LUHN algorithm to verify a card number, you can let a customer know their card number is invalid before taking payment through a gateway. After all, it’s a better user experience if they don’t have to wait for the server to try and authorize their card through a payment gateway with incorrect details that could have been detected using a simple LUHN check!
C#
public static class LuhnUtility { public static bool IsCardNumberValid(string cardNumber, bool allowSpaces = false) { if (allowSpaces) { cardNumber = cardNumber.Replace(" ", ""); } if (cardNumber.Any(c => !Char.IsDigit(c))) { return false; } int checksum = cardNumber .Select((c, i) => (c - '0') << ((cardNumber.Length - i - 1) & 1)) .Sum(n => n > 9 ? n - 9 : n); return (checksum % 10) == 0 && checksum > 0; } }
Javascript:
function isCardNumberValid(cardNumber, allowSpaces) { if (allowSpaces) { cardNumber = cardNumber.replace(/ /g, ''); } if (!cardNumber.match(/^\d+$/)) { return false; } var checksum = 0; for (var i = 0; i < cardNumber.length; i++) { var n = (cardNumber.charAt(cardNumber.length - i - 1) - '0') << (i & 1); checksum += n > 9 ? n - 9 : n; } return (checksum % 10) == 0 && checksum > 0; }
No comments:
Post a Comment