How to Validate Phone Number in Java


Here this example will explain how to validate phone number in Java.

Source Code

package com.beginner.examples;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ValidatePhone {

	public static void main(String[] args) {
		String phone = "13900442200";
		String phone2 = "021-88889999";
		String phone3 = "88889999";
		String phone4 = "1111111111";
		 
		if(isPhone(phone) || isMobile(phone)){
			System.out.println("1This is correct.");
		}
		
		if(isPhone(phone2) || isMobile(phone2)){
			System.out.println("2This is correct.");
		}
		
		if(isPhone(phone3) || isMobile(phone3)){
			System.out.println("3This is correct.");
		}
		
		if(isPhone(phone4) || isMobile(phone4)){
			System.out.println("4This is correct.");
		}else{
			System.out.println("This is incorrect.");
		}
	}
	
	public static boolean isMobile(final String str) {
		Pattern p = null;
		Matcher m = null;
		boolean b = false;
		p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); 
		m = p.matcher(str);
		b = m.matches();
		return b;
	}
	
	public static boolean isPhone(final String str) {
		Pattern p1 = null, p2 = null;
		Matcher m = null;
		boolean b = false;
		p1 = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$"); 
		p2 = Pattern.compile("^[1-9]{1}[0-9]{5,8}$");     
		if (str.length() > 9) {
			m = p1.matcher(str);
			b = m.matches();
		} else {
			m = p2.matcher(str);
			b = m.matches();
		}
		return b;
	}
}

Output:

1This is correct.
2This is correct.
3This is correct.
This is incorrect.

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments