Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

phone Number validation in java

I want to validate a phone number in such Way :-

The field should allow the user to enter characters and should auto-correct. So an entry of "+1-908-528-5656" would not create an error for the user, it would just change to "19085285656".

I also want to number range between 9 to 11.

I also tried with the below code but not concluded to the final solution:

 final String PHONE_REGEX = "^\\+([0-9\\-]?){9,11}[0-9]$";
 final Pattern pattern = Pattern.compile(PHONE_REGEX);
 String phone = "+1-908-528-5656";      
 phone=phone.replaceAll("[\\-\\+]", "");
 System.out.println(phone);
 final Matcher matcher = pattern.matcher(phone);
 System.out.println(matcher.matches()); 
like image 374
Devendra Avatar asked Dec 24 '14 04:12

Devendra


3 Answers

You can use simple String.matches(regex) to test any string against a regex pattern instead of using Pattern and Matcher classes.

Sample:

boolean isValid = phoneString.matches(regexPattern);

Find more examples

Here is the regex pattern as per your input string:

\+\d(-\d{3}){2}-\d{4}

Online demo


Better use Spring validation annotation for validation.

Example

like image 79
Braj Avatar answered Sep 22 '22 19:09

Braj


// The Regex not validate mobile number, which is in internation format.
// The Following code work for me. 
// I have use libphonenumber library to validate Number from below link.
// http://repo1.maven.org/maven2/com/googlecode/libphonenumber/libphonenumber/8.0.1/
//  https://github.com/googlei18n/libphonenumber
// Here, is my source code.

 public boolean isMobileNumberValid(String phoneNumber)
    {
        boolean isValid = false;

        // Use the libphonenumber library to validate Number
        PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
        Phonenumber.PhoneNumber swissNumberProto =null ;
        try {
            swissNumberProto = phoneUtil.parse(phoneNumber, "CH");
        } catch (NumberParseException e) {
            System.err.println("NumberParseException was thrown: " + e.toString());
        }

        if(phoneUtil.isValidNumber(swissNumberProto))
        {
            isValid = true;
        }

        // The Library failed to validate number if it contains - sign
        // thus use regex to validate Mobile Number.
        String regex = "[0-9*#+() -]*";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(phoneNumber);

        if (matcher.matches()) {
            isValid = true;
        }
        return isValid;
    }
like image 29
jessica Avatar answered Sep 22 '22 19:09

jessica


Assuming your input field take any kind of character and you just want the digits.

 String phone = "+1-908-528-5656";
 phone=phone.replaceAll("[\\D]","");
 if(phone.length()>=9 || phone.length()<=11)
   System.out.println(phone);
like image 23
Md. kamrul Hasan Avatar answered Sep 21 '22 19:09

Md. kamrul Hasan