creditcard2 validator determining major credit card types based on number

creditcard2 validator determining major credit card types based on number

The creditcard2 jQuery validator extension improves on the normal one by allowing dashes and spaces in credit card number fields and also by marking some invalid numbers (which slip by the normal validator plugin) as invalid.

One requirement of the creditcard2 validation rule is that the credit card type be passed in as a parameter.  Some (all?) cards can, however, be identified based on their number pattern.  Therefore, I wrote a simple function that returns the card type in a format the creditcard2 plugin supports, for the cards I am personally interested in.  Extending to other cards should be trivial.  

Here's a function to do it:

     /* use regular expressions to determine credit card type based on the number */
     function creditCardTypeFromNumber(num) {
       // first, sanitize the number by removing all non-digit characters.
       num = num.replace(/[^\d]/g,'');
       // now test the number against some regexes to figure out the card type.
       if (num.match(/^5[1-5]\d{14}$/)) {
         return 'MasterCard';
       } else if (num.match(/^4\d{15}/) || num.match(/^4\d{12}/)) {
         return 'Visa';
       } else if (num.match(/^3[47]\d{13}/)) {
         return 'AmEx';
       } else if (num.match(/^6011\d{12}/)) {
         return 'Discover';
       }
       return 'UNKNOWN';
     }