user53794
user53794

Reputation: 3830

Javascript regex to detected possible credit card numbers

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:

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!

Upvotes: 4

Views: 5572

Answers (5)

Chris Harris
Chris Harris

Reputation: 4735

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

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

Upvotes: 1

Josh Stodola
Josh Stodola

Reputation: 82483

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.

Upvotes: 1

cletus
cletus

Reputation: 625077

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

Upvotes: 2

Nick Lewis
Nick Lewis

Reputation: 4230

/(?:\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.

Upvotes: 0

Samir Talwar
Samir Talwar

Reputation: 14330

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?

Upvotes: 1

Related Questions