4

When a user submits a form I need to make sure that the input contains at least a minimum number of digits. The problem is that I don't know what format the input will be in. The digits likely won't be in a row, and might be separated by letters, punctuation, spaces, etc. I don't care about the rest of the string.

I'd like to check this with a RegularExpressionValidator but I'm not quite sure how to write the regex.

I guess this would be similar to a phone number regex, but a phone number at least has some common formats.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Brandon
  • 68,708
  • 30
  • 194
  • 223

3 Answers3

13

The following will match an input string containing at least n digits:

Regex.IsMatch(input, @"(\D*\d){n}");

where n is an integer value.

A short explanation:

  • \D* matches zero or more non-digit chars (\D is a short hand for [^0-9] or [^\d]);
  • so \D*\d matches zero or more non-digit chars followed by a digit;
  • and (\D*\d){n} groups, and repeats, the previous n times.
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
  • i pondered this for a while and reached the conclusion that it couldn't be done without a repetitive pattern. but once you see it it's strikingly obvious. elegant! +1 – David Hedlund Jul 13 '10 at 14:58
  • @David, thanks! @annakata, I've added more explanation to my post. – Bart Kiers Jul 13 '10 at 15:02
  • Thanks, Bart! I have to agree with what David said. Nice solution :) – Brandon Jul 13 '10 at 15:07
  • @Bart, is there a way to make this take in a minimum instead of a set number? I tried replacing `{n}` with `{n,}`, but that breaks it. It starts counting the non-digits as well. – Brandon Jul 13 '10 at 15:11
  • I'm not too familiar with the .NET regex engine, but I'd say `{n,}` should worl as well. AFAIK, `@"(\D*\d){n}"` causes the engine to look for **at least** `n` occurrences of `(\D*\d)` so it wouldn't make any difference to use either `{n}` or `{n,}`. Sorry I can't be of any more assistance! – Bart Kiers Jul 13 '10 at 15:30
3

I would approach it something like this:

Regex.IsMatch(input, @"^([^0-9]*[0-9]){10}.*$");

In words, this would search for 10 digits, each of which are surrounded by 0 or more characters. Since the .* are greedy, any additional digits would be matched by them as well.

Anyway, check out http://regexlib.com/RETester.aspx It can be really hard to write a regular expression without something to test against.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Slider345
  • 4,558
  • 7
  • 39
  • 47
  • +1, thanks for the help. I've been using regexpal.com, but that one looks a little better. Thanks for the link. – Brandon Jul 13 '10 at 15:05
0

in order to have at least n digits, you need to use following regex:

(\D*\d){n,}

Regex (\D*\d){n} will match exactly n digits.

Regards, Karlo.

Karlo Smid
  • 525
  • 1
  • 5
  • 13