How do I create a regular expression that validates Spanish mobile phone numbers?
They must follow the following rules.
At the beginning:
- [optional]
+34
- [optional]
34
- [optional]
0034
From here you should have:
- Exactly 9 numbers (spaces and hyphens are allowed)
- The first number must be
6
or7
Valid:
666444555
666-444-555
666 44 45 55
666-44-45-55
+34666555444
0034666555444
Not valid
935554488
+44777555444
800444666
635*554*488
635/554/488
NOTE: It's labeled java because that's how I'm going to parse
String
it and if you want to show code. Of course, it is not strictly necessary, with the regular expression I have enough.
This regular expression should do the trick:
I don't have a Java environment handy, but all the mentioned test cases pass in the RegexPlanet tool .
I recommend you to use
libphonenumber
( Google's library to validate phone numbers). It has many advantages compared to doing your own implementation, for example that you don't have to maintain it yourself and that it gives you the number in international format, no matter how the user enters it.An example of how it is used is:
Now there are a number of methods but the most important would be:
If you want to see the number in international format:
To see a demo and test if it exactly meets all your requirements, you can go here .