Reputation: 6457
I need to handle phone number with international codes but I don't need the phone to be a specific format. I've found numerous example on how to apply it for the US, Spain, etc... but none that just allow to enter a number with 00 or +, allow spaces and/or dashes or no space or dashes.
I've got the following expression applied on a Telephone number field in an asp.net MVC 5 application:
[RegularExpression(@"^\+?\d*$", ErrorMessage = "Not a valid Telephone number.")]
At it stands, it handles the following scenarios:
+19999999999
0019999999999
which is fine but it doesn't allow spaces and/or dashes so numbers such as this one:
+ 1 999 999 99 99
+32 999-999-99-99
+7 999 999-99-99
are not considered valid.
How can allow spaces and/or dashes to be included. More specifically, is it possible to ensure that:
If 1. is too complicated, can you just tell me how to allow spaces and/or dashes without any specific rules, so a number such as this: -33-999 999+99-99, while being totally wrong will still be valid.
Thanks
Upvotes: 1
Views: 8811
Reputation: 1492
^(?!\b(0)\1+\b)(\+?\d{1,3}[. -]?)?\(?\d{3}\)?([. -]?)\d{3}\3\d{4}$
This works for number digit validation, country code and it's length.
Upvotes: 0
Reputation: 6457
This is the closest I've managed to get my RegEx to work after trying it out on [enter link description here][regexr] as suggested by @mlkptl35
^([+]|[00]{2})([0-9]|[ -])*
It will allow the string to:
Either start with a + or 00 for the international part, followed by up to 3 digits
Allow any digits, space or - thereafter
With the above RegEx, I was able to handle the following numbers:
+32999999
+1-99-999-99-99
+33 99-999-99-99
+7 999999999
+44 999999999
+353 99-9999999
+1 99-999-9999
0044999999999
00353 99-999 9999
and so on.
I'm sure it's far from perfect but I'm just learning, so apologies in advance to all the "RegEx" experts out there.
If I have time to improve it, I'll provide updates.
Upvotes: 1
Reputation: 11
in above regx
\s is used to check for any whitespace
(\s)? means there can be whitespace or maybe not
for validating length you can replace * with {rang start,rang end} example {10,20}
\d{3} means accepts only 3 digit in that place
========================================================================
you can use this website for testing http://regexr.com/
Refer this image for more information
Regx Tested
Rest is upto you. You can build your own required regx once you learn it you should check regular expression cheatsheet on above mention website.It will help a lot.
Upvotes: 1