English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I'm a moderately advanced beginner with regex, and I've come up with this one I'm pretty sure will work, but I'd appreciate a proofreading before going live with it:
^[0-9, ]+$
It should match if the value is all numbers and/or spaces, but is it effecient as it could be?

Should I include dashes too?

And what if the value has no numbers? (I guess I could check first for all spaces & dashes and handle that case differently. No sense in telling the customer they've entered a CC# where it shouldn't be if they've not entered any digits.)

Thanks!

2006-09-19 08:16:11 · 2 answers · asked by John's Secret Identity™ 6 in Computers & Internet Programming & Design

Note that I'm not trying to validate a card #. I'm just trying to detect when the customer *tries* to type in a card # in the wrong place, even if they misstype the number.

Also note that Amex #s aren't given in 4x4 format. And our site will accept #s entered with or without spaces and/or dashes anyway, so the expression aught to detect anything that it would accept.

2006-09-23 13:01:02 · update #1

2 answers

It actually needs to be ^[0-9, ]\+$
Checking for dashes would be optional.

This would check for only 4, 4 digit numbers separated by dashes:

^\([0-9]\{4\}-\)\{3\}
[0-9]\{4\}$

2006-09-22 09:34:15 · answer #1 · answered by Will 6 · 0 0

If you're looking purely for efficiency, my answer may not be the best, but I think it's best to start with something long that actually works, and then do some testing and trim it down. For example...

/^[4-5]{1}[0-9]{3}[ -]{0,1}[0-9]{4}[ -]{0,1}[0-9]{4}[ -]{0,1}[0-9]{4}$/

Tests to see if the first digit is a 4 or 5, that all numbers are clustered in 4 groups of four, and the separation character can either be non-existent, or be a - or a space.

Further tests might be that the separation character must be the same throughout the string, rather than, say, a space for the first cluster and a dash for the second.

I've written a PHP-based utility to test regular expressions via the preg_match() function. You might want to have a peek.

2006-09-23 17:00:36 · answer #2 · answered by Anonymous · 0 0

fedest.com, questions and answers