views:

434

answers:

5

I'm having no end of trouble coming up with an appropriate regex or set of regex's.

What I want to do is detect:

  • Detect contineous run of digits of length 13 through 19
  • Detect contineous run of digits interspersed with whitespace of length 13 through 19
  • Detect contineous run of digits interspersed with dashes of length 13 through 19

The basic business requirement is to warn a user that they may have entered a credit card number in a text field and they ought not to do that (though only a warning, not a hard error). The text field could span multiple lines, could be up to 8k long, a CC # could be embedded anywhere (unlikely to split across multiple lines), could be more than 1 CC# (though detecting the prescence of at least 1 is all I need. I don't need the actual value). Don't need to validate check digit.

The length check can be done external... ie I'm happy to loop through a set of matches, drop any whitespace/dashes and then do a length comparison.

But... JavaScript regex is defeating my every attempt (just not in the right "head space") so I thought I'd ask here :)

Thanks!

+1  A: 

Seems like a fairly simple regex. I've made your requirements a little more stringent - as it was, you'd match lists of dates, such as "1999-04-02 2009-12-09 2003-11-21". I've assumed the sections will be in three to six groups and will themselves be groups of three to eight numbers/dashes/whitespace. You can tune these numbers fairly easily.

/[0-9]{13,19}|([0-9- ]{3,8}){3,6}/

I'm not sure this is what you want, but I figured it was worth a go. If this isn't what you're looking for, perhaps you could show us some regexes that come close or give an impression of what you want?

Samir Talwar
A: 
/(?:\d[ -]?){12,18}\d/

Checks for 13-19 digits, each of which digit (except the last) may have a space or dash after it. This is a very liberal regex, though, and you may want to narrow it down to known actual credit card formats.

Nick Lewis
+2  A: 

Here are all the rules required for credit card validation. You should be able to easily do this in Javascript.

cletus
+1  A: 

You want to regex 8k of text with Javascript? Don't waste your time (or the users poor CPU) doing this with Javascript. You're gonna need server-side validation anyways, so just leave it to that.

Josh Stodola
8K is the upper limit, and very unlikely to be reached. I would not think a regex against 8K would bring a PC to it's knees for any amount of time. Are you certain of this?
The bottom line is that server-side validation is required. You are gaining *very* little by subjecting the client to such operations.
Josh Stodola
+1  A: 

Here is a great script for many credit card validation steps.

http://javascript.internet.com/forms/val-credit-card.html

Chris Harris
Not looking to validate a cc #. Thanks though.