Hi,
what would the pattern be for credit cards?
I'm trying to validate credit card field, and Private number looks like the best module. But can not figure out how to build a pattern for a credit card (especially since there are more than one kind of credit card, each with a different pattern)?
or maybe there's a different cck field type I should use?
Thanks in advance for your help!
:)
Scott

Comments

john.money’s picture

Hi Scott.

I am in the process of updating Private Number and will be sure to include some documentation about credit card regex in the next releae. There can be quite a bit of logic behind credit card validation, so there will likely not be a one-size-fits-all regex solution. For example, here is some code I dug up from a prior ecommerce project:

   if (type == "Visa") {
      // Visa: length 16, prefix 4, dashes optional.
      var re = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "MC") {
      // Mastercard: length 16, prefix 51-55, dashes optional.
      var re = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "AmEx") {
      // American Express: length 15, prefix 34 or 37.
      var re = /^3[4,7]\d{13}$/;
   } else if (type == "Disc") {
      // Discover: length 16, prefix 6011, dashes optional.
      var re = /^6011-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "Diners") {
      // Diners: length 14, prefix 30, 36, or 38.
      var re = /^3[0,6,8]\d{12}$/;
   }

I found the following regex for Amex, Visa and Mastercard (not Discover or Diners) which does not capture the nuances of the above code, but might work as a first pass. I have yet to test it:

((4\d{3})|(5[1-5]\d{2}))\-(\d{4}\-){3}|^(3[4,7]\d{2})\-\d{6}\-\d{5}
john.money’s picture

Status: Active » Closed (fixed)
hacmx’s picture

This pattern work for me:

For Visa, MasterCard :
((4\d{3})|(5[1-5]\d{2}))( |)?\d{4}(\4\d{4}){2}

For Visa, MasterCard, Discover:
((4\d{3})|(5[1-5]\d{2})|(6011))( |)?\d{4}(\5\d{4}){2}

based on: http://www.explainth.at/en/re/repats.shtml

cheers!