Friday, July 27, 2012

Validate Phone number in Java

If you are developing standalone java application or web application, there will be cases you come across where you require to validate phone numbers according to different formats.

 Phone number can have formats as (nnn)nnn-nnnn or nnnnnnnnnn or nnn-nnn-nnnn
or as per your requirement :)

Explanation to Regular expression  ^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$ is :
1. ^\\(? - May start with an option "("
2. (\\d{3}) - Followed by 3 digits
3.  \\)? - May have an optional ")"
4. [- ]? : May have an optional "-" after the first 3 digits or after optional ) character
5. (\\d{3}): Followed by 3 digits
6. [- ]? - May have another optional "-" after numeric digits
7. (\\d{4})$ : ends with four digit

Java Program to validate Phone Number :

package com.anuj.utils;

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

public class PhonenumberValidation {
    static Pattern p;
    static Matcher m;

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String phoneno = "(123)456-7890";
        // String phoneno = "123-456-7890";
        // String phoneno = "1234567890";

        boolean validPhone = isPhoneNumberValid(phoneno);
        if (validPhone) {
            System.out.println("Phone number is valid");
        } else {
            System.out.println("Phone number is not valid");
        }
    }

    public static boolean isPhoneNumberValid(String phoneNumber) {
        boolean isValid = false;

        String exp = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$";
        CharSequence str = phoneNumber;
        p = Pattern.compile(exp);
        m = p.matcher(str);
        if (m.matches()) {
            isValid = true;
        }
        return isValid;
    }

}


Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/