-2

I need to build a regex to validate all types of phone numbers which includes + ( ) . -

Thanks to Google and stack overflow and i got a regex

/^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]*$/g

to validate all phone numbers.

But while validating +(123 456-7890 the above regex not works as expected. So I modified the above regex as

/^\+?([(]{1}[0-9]{1,3}[)]{1}|[0-9]{1,3})([-\s0-9]*|[.\s0-9]*)\d+$/

and it works fine.

Now I need to restrict the user from entering consecutive - and dots(.)

So I manually validating that

if(HomePhone.indexOf("..") > -1 && HomePhone.indexOf("--") > -1) 
return false;

Could anyone help me to solve the above issue using a single regex by improving it..?

Thanks in Advance

prasanth
  • 22,145
  • 4
  • 29
  • 53
  • The way you are restricting the user not to give more than 3 consecutive digits, you can do that for the hyphens and dots, right? Think about it. – Wasi Ahmad Nov 04 '16 at 07:05
  • i have't give you down vote. try this link http://stackoverflow.com/questions/22378736/regex-for-mobile-number-validation – Nitin Kumar Nov 04 '16 at 07:06
  • @WasiAhmad the user can have space, periods and hypens but not consecutive. He can enter consecutive numbers – Manikandan Sekar Nov 04 '16 at 07:07
  • @NitinKumar thanks for the link. let me see and try that out – Manikandan Sekar Nov 04 '16 at 07:10
  • @ManikandanSekar i can understand, the location of the space, periods and hyphens are also fixed. You just need to make sure user is restricted to put more than one hyphens or dots consecutively which is same what you have done for digits. – Wasi Ahmad Nov 04 '16 at 07:11
  • (123) 456-7890 +(123) 456-7890 +(123)-456-7890 +(123) - 456-7890 +(123) - 456-78-90 123-456-7890 123.456.7890 1234567890 +31636363634 075-63546725 I need to write a regex to allow all the above cases and restrict the user from entering double (-) and (.) Also if it contains open brackets, must have a close bracket – Manikandan Sekar Nov 04 '16 at 07:15
  • @ManikandanSekar i have added answer, you can check if that helps you. – Wasi Ahmad Nov 04 '16 at 07:42

2 Answers2

0

use to match .. and -- use regex /(\.\.+|\--+)/g

Demo Here

prasanth
  • 22,145
  • 4
  • 29
  • 53
  • Thanks for the quick reply. as I mentioned in the post I need to validate multiple fields using the same regex so I removed the g flag. I will try this – Manikandan Sekar Nov 04 '16 at 07:12
0

I believe the following regular expression will satisfy all your requirements.

Regex: ^\+?(\([0-9]{3}\)|[0-9]{3})(-. )?[0-9]{3}(-. )?[0-9]{4}$

This regex should accept the following:

(123) 456-7890 
+(123) 456-7890 
+(123)-456-7890 
123-456-7890 
123.456.7890 
1234567890 
+3163636363 
075-6354672

You can modify this expression to adapt to your requirements, if required.

Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161