Hanalei Hanalei - 1 year ago 84
Java Question

Use regex to validate a phone number?

if((phone.length() > 10 &&
((phone.contains("+1" + "((\\\\d{3}-)){1,2}\\\\d{4}"))
|| (phone.contains("+966" + "d{9}"))))
|| ((phone.length() == 10) &&
!(phone.contains("(") && !(phone.contains(")") &&
!(phone.contains("-")))))) //phone doesnt contain special characters if its a saudi no.
else {

Hello all :) I'm trying to create a code that validates the following formats of phone numbers and NOTHING else:

  1. +9665xxxxxxxx

  2. 05xxxxxxxx

  3. +1(xxx)xxx-xxxx

  4. +1xxxxxxxxxx

  5. xxx-xxx-xxxx

I've tried to do this in the code above, where the phone number is represented as String "phone". However I think I've done it incorrectly, especially the regex. Can anyone tell me if there is a simpler way to do this? Or a simplified version of the code? Would it be easier if I used a series of if() statements instead? I'm sorry I'm very new to java so I'm sure I've done something wrong.

Answer Source

Something like this should do the trick:

Pattern pattern = Pattern.compile(
Matcher matcher = pattern.matcher("+966512345678");


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download