0

I'm trying to validate a textbox containing a variety of acceptable 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!!

2 Answers 2

3

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])?)?$
Sign up to request clarification or add additional context in comments.

3 Comments

This one allows me to have options 2 and 3 from my list, but not option 1
@Brett My second example should allow you to have option 1 as well. You can test it here: rubular.com/r/bxFzEVFMZO
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!
1
^(?:[0-9]{9}\+[0-9])?$

1 Comment

Like Brian, this one allows me to have options 2 and 3 from my list, but not option 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.