Skip to content

Instantly share code, notes, and snippets.

@sangramanand
Created February 23, 2012 11:46
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save sangramanand/1892516 to your computer and use it in GitHub Desktop.
Save sangramanand/1892516 to your computer and use it in GitHub Desktop.
Validating phone number using Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author anand
*/
public class ValidatePhoneNumber {
public static void main(String[] argv) {
String phoneNumber = "1-(80..2)-321-0361";
System.out.println(phoneNumber.length());
String regex = "^\\+?[0-9. ()-]{10,25}$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(phoneNumber);
if (matcher.matches()) {
System.out.println("Phone Number Valid");
} else {
System.out.println("Phone Number must be in the form XXX-XXXXXXX");
}
}
}
@sangramanand
Copy link
Author

The regex code accepts a phone number between 10-25 chars length. The chars can be numbers, parentheses(), hypens, periods & may contain + sign in the beginning and can contain whitespaces in between.

The valid phone numbers with the above regex validations are

  1. +33 (0)1 60 72 91 62 - Mary contact number
  2. 1-(802)-321-0361 - General sentiment contact number
  3. 080-41483223 - Indavest land line
  4. 1-(802)-321..0361 - Random contact number

@tankchintan
Copy link

Does it work with -

  1. 8128128122
  2. 812 787 7898
  3. 812 897-8978

@sangramanand
Copy link
Author

yup! all the three numbers works with the above validation.

@myexternall11
Copy link

Hi please help me.

how I can prompt the use that the phone number he/she input is invalid?

I need to put the codes here
private void saveButton3ActionPerformed(java.awt.event.ActionEvent evt) {.....}

@ainie89
Copy link

ainie89 commented Aug 15, 2014

Hi.
Need help here.
I have 2 input text where user must enter their phone number. Then if the phone number is match, it will go to other page, if not the user must re-enter the phone number. The problem is, how to compare the value that entered by the user and verify whether it is match or not?

Copy link

ghost commented Jan 28, 2018

@ainie89
you can achieve this by using this simple logic.

if( ! textField2.getText().toString().matches(textField1))
{
// do this..
}

hope it helps.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment