0

I need a reg-ex for JCB card validation with this rule, (Reference for JCB format)

First four digits must be 3088, 3096, 3112, 3158, 3337, or the first eight digits must be in the range 35280000 through 35899999. Valid length: 16 digits.

Many posts are found with Regex ^(?:2131|1800|35\d{3})\d{11}$ referring to post1, post2 and post3.

I am building a credit card payment module using Authorize.Net.But the Authorize.Net test JCB credit card validation fails for above Regex (^(?:2131...).

But there are JCB cards like 3088000000000017 (Authorize.Net test card), 3096022966045455,3088810779293696.

Help me with the Regex. I could not find any JCB cards with 2131 or 1800, am I missing something.

Community
  • 1
  • 1
Dhanuka777
  • 8,331
  • 7
  • 70
  • 126
  • I would highly recommend against using a regex for such validations. You should parse the input to a number and handle it. The regex for matching numeric ranges is very opaque and non-intuitive; in short a maintenance nightmare. – Vikhram Feb 23 '16 at 01:34
  • 1
    @Vikhram: I strongly disagree. When there are strict rules on the format of a string of digits (or any characters) and those rules are not bound to change that often, regex can be very helpful in identifying valid strings. Of course in case of credit card numbers and other strings of digits carrying error detection, one should also validate the check digit to make sure the number is actually a valid one, but you save time if you check only those that are otherwise of valid format. – xjuice Feb 23 '16 at 01:47

1 Answers1

4

Given the rules I would use this regex:

^(3(?:088|096|112|158|337|5(?:2[89]|[3-8][0-9]))\d{12})$

Breakdown:

  • ^(3...)$: Anchor start and end and capture the content beginning with digit 3

  • (?:...): Don't capture content explicitly (captured within outer parenthesis)

  • 088|...|337|...: Match any of the three-digit values or

  • 5(?:...): First match 5 and then

  • 2[89]|[3-8][0-9]: Match either 2 followed by 8 or 9, or any digit from 3 to 8 followed by any digit (from 0 to 9)

  • \d{12}: Followed by exactly 12 any digits (\d is the same as [0-9])

EDIT: Regarding your question about numbers starting with 2131 and 1800, it reads in your third reference page that those JCB card numbers are 15 digits long, while ones beginning with 35 are 16 digits long. If your specifications refers to only 16 digit long numbers, then you probably won't need to match those shorter ones.

xjuice
  • 300
  • 1
  • 8