Permalink
Browse files

[api] Added missing validate and pan function

  • Loading branch information...
1 parent 4430507 commit 9cb559ed9529bb5919c69a2aa9255c71f653a5e9 @3rd-Eden 3rd-Eden committed Dec 1, 2012
Showing with 43 additions and 3 deletions.
  1. +43 −3 lib/creditcard.js
View
@@ -82,16 +82,56 @@ exports.format = function format(number) {
};
/**
+ * Validates the creditcards using the Luhn10 algorithm.
+ *
+ * @copyright https://gist.github.com/976805
+ * @param {String} number
+ * @returns {Boolean}
+ */
+exports.validate = function validate(number, b, c, d, e) {
+ for (d = +number[b = number.length - 1], e = 0; b--;) {
+ c = +number[b];
+ d += ++e % 2 ? 2 * c % 10 + (c > 4) : c;
+ }
+
+ return !(d % 10);
+};
+
+/**
+ * Applies PAN truncation to the given creditcard. PAN (primary account number)
+ * trunction is a "technology" that prevents most of the digits of a creditcard
+ * from appearing on printed receipts.
+ *
+ * @param {String} number
+ * @return {String} pan
+ */
+exports.pan = exports.PAN = function pan(number) {
+ var pattern = exports.format(number)
+ , keep = pattern.slice(-4);
+
+ return pattern.slice(0, -4).replace(/\d/g, function replace() {
+ return 'X';
+ }) + keep;
+};
+
+/**
+ * Parse the creditcard information
*
* @param {String} number
* @returns {String}
*/
exports.parse = function parse(number) {
number = number.replace(/\D/g, '');
+ var scheme = exports.cardscheme(number);
+
return {
- iin: number.slice(0, 9) // issuer identifier number
- , mii: exports.mii[+number.charAt(0)] // major industry identifier
- , formatted: exports.format(number) // formatted version
+ iin: number.slice(0, 9) // Issuer Identifier Number
+ , mii: exports.mii[+number.charAt(0)] // Major Industry Identifier
+ , formatted: exports.format(number) // Formatted version
+ , cvv: scheme === 'American Express'
+ ? 4 // American Express requires 4 digits
+ : 3 // All other credit cards
+ , pan: exports.pan(number) // PAN truncated version
};
};

0 comments on commit 9cb559e

Please sign in to comment.