4

I was using RegEx to validate user phone numbers. I have set of requirements for phone number validation. I dont have much idea about the RegEX. can anyone help me to provide a matching reqex for my requirement. Here the validation is very simple.

Conditions

 1. It should allow numbers from 0-9.
 2. It should allow + sign. (+ sign is not mandatory but not allow after even a single letter (ie: should be placed at front.)).
 3. It should allow - sign. (- sign is also not mandatory and can be placed anywhere)
 4. It should allow empty space everywhere.
 5. No dots or no other chars allowed except the above said things.

Correct values

+65-12345678
65-12345678
6512345678
65 12345678
65 123 45678
65 123-45678
+65 123-45678
1234

InCorrect values

12345+86666
123alpha

Thanks

1
  • Firstly, be specific about the rules for validations i.e. which patterns do you want to match. Secondly, please try posting what have you tried so far, and what's the problem you are facing. Commented Mar 5, 2013 at 10:56

3 Answers 3

8

Based on your samples, try this:

^(?:\+?\d{2}[ -]?\d{3}[ -]?\d{5}|\d{4})$

It will match all the correct values.

DESCRIPTION:

Regular expression visualization

DEMO:

http://regexr.com?340nf

Sign up to request clarification or add additional context in comments.

2 Comments

1up for the explanatory diagram :)
This is a great answer because it directly answers the OP while also providing a clear explanation that is a good resource for those learning regex.
7

Just to help you build some concepts.
The following regex would match the first seven inputs you provided.

/^\+?\d{2}[- ]?\d{3}[- ]?\d{5}$/

\+? would match a + sign. The ? in it makes the + sign optional.
\d{2} matches two digits
[- ]? matches either a - or a (space). ? makes the occurrence of - or (space) optional.
\d{5} then matches 5 digits.
^ and $ are the start and end anchors.

Comments

3

based on you samples try this pattern.

^(?:\+?\d{2}[ -]?[\d -][\d -]+)$

Comments

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.