2

I am using a regular expression ^4[0-9]{15}$ to check credit card information starting with 4 for VISA and that are 16 digits long.

This expression accepts credit card numbers like 4141414141414141aa which is wrong, as it accepts alpha-characters in the end of a valid credit card number.

How do I fix this?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
PC2015
  • 977
  • 1
  • 6
  • 10
  • 1
    The regex by itself looks fine. Can you show how you are using this in your code? – ig0774 Jul 27 '12 at 22:34
  • 1
    What you are describing is very much impossible. That regex you have should not, by any means, allow anything after a total of 16 numbers. – Palladium Jul 27 '12 at 22:35
  • In what programming language, or what regex package? – Stephen P Jul 27 '12 at 22:37
  • I am using Javascript .. Not sure why I am able to enter these values – PC2015 Jul 28 '12 at 01:05
  • 1
    Curious... Does the *input field* allow you to enter the non-digit characters, or is the value with non-digit characters passing the *validation check*? – TLS Jul 30 '12 at 16:47
  • Possible duplicate of [How do you detect Credit card type based on number?](http://stackoverflow.com/questions/72768/how-do-you-detect-credit-card-type-based-on-number) – Mariano Nov 20 '15 at 01:36
  • You should probably allow spaces in the credit card input. Otherwise you are going to annoy at lot of people (and it is bad UX). – nils Dec 01 '15 at 08:03

2 Answers2

0

If you're working in Java, anchors are not ^ and $, but \A and \z, so your regex would be

"\\A4[0-9]{15}\\z"

or

"\\A4\\d{15}\\z"

In Javascript the anchors should indeed be ^ and $ making the regular expression:

/^4\d{15}$/

Tested in my Firebug Javascript console:

>>> var val1='4141414141414141';
>>> var val2='4141414141414141aa';
>>> /^4\d{15}$/.test(val1);
true
>>> /^4\d{15}$/.test(val2);
false
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
Stephen P
  • 14,422
  • 2
  • 43
  • 67
  • Thanks for your replies. I am using Javascript to check the regex and html is the front end where user inputs data. Since you all have validated that this expression is right, i should probably check other parts of my code for errors. Many Thanks! – PC2015 Jul 28 '12 at 01:06
  • @user997509 - maybe you could include some code to show exactly when and how you're checking for a match. – Stephen P Jul 30 '12 at 16:35
0

You can use \b to match the start and end of a word in JavaScript. So it can be:

if (/\b4\d{12}(?:\d{3})?\b/.test(subject)) {
    // Successful match

} else {
    // No match

}

according to http://tools.twainscanning.com/getmyregex

Woodrow Norris
  • 237
  • 2
  • 12