tags:

views:

25

answers:

2

I'm trying to validate a textbox containing a variety of accepable inputs:

  • "123456789"
  • "123456789+1"
  • ""

I'm using this regular expression to validate the first two conditions:

^[0-9]{9}\+[0-9]$

But now I can't figure out how to allow the user not to enter anything, I've tried things like encapsulating the expression in ()? , or changing the {9} to {0,9}, but this allows for a variable number of numbers in the first group (as it MUST be 9, or none)

Any help would be greatly appreciated!!

+3  A: 

Try

^([0-9]{9}\+[0-9])?$

The ? means "0 or 1 copies of the preceding expression." In this case, the entire parenthesized expression is made optional.

Also, if you want the \+[0-9] part to be optional, you will likely want to do the same to that; wrap in in parentheses and make it optional with ?:

^([0-9]{9}(\+[0-9])?)?$
Brian Campbell
@Brian - This one allows me to have options 2 and 3 from my list, but not option 1
Brett
@Brett My second example should allow you to have option 1 as well. You can test it here: http://rubular.com/r/bxFzEVFMZO
Brian Campbell
@Brian - Wonderful, thanks!! yeah, that makes sense to have the second part in parenthesis too, I've been reading about these and feel like I'm learning a bit, but keep getting hic-cups.. thanks!
Brett
+1  A: 
^(?:[0-9]{9}\+[0-9])?$
Charles
@Charles - Like Brian, this one allows me to have options 2 and 3 from my list, but not option 1
Brett