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
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
Share Improve this question edited Mar 6, 2013 at 12:33 UniqueChar asked Mar 5, 2013 at 10:49 UniqueCharUniqueChar 1952 gold badges2 silver badges14 bronze badges 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. – Ali Shah Ahmed Commented Mar 5, 2013 at 10:56
3 Answers
Reset to default 8Based on your samples, try this:
^(?:\+?\d{2}[ -]?\d{3}[ -]?\d{5}|\d{4})$
It will match all the correct values.
DESCRIPTION:
DEMO:
http://regexr.com?340nf
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.
based on you samples try this pattern.
^(?:\+?\d{2}[ -]?[\d -][\d -]+)$