Валидация номера телефона 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()); 

eatSleepCode's user avatar

eatSleepCode

4,3776 gold badges42 silver badges89 bronze badges

asked Dec 24, 2014 at 4:54

Devendra's user avatar

3

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

answered Dec 24, 2014 at 5:08

Braj's user avatar

BrajBraj

46.2k5 gold badges58 silver badges74 bronze badges

2

// 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;
    }

answered Jan 21, 2017 at 9:18

jessica's user avatar

jessicajessica

1,7001 gold badge13 silver badges17 bronze badges

1

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);

answered Dec 24, 2014 at 6:24

Md. kamrul Hasan's user avatar

We can use String.matches(String regex)1 to validate phone numbers using java.

Sample code snippet

package regex;

public class Phone {
    private static boolean isValid(String s) {
        String regex = "\d{3}-\d{3}-\d{4}"; // XXX-XXX-XXXX
        return s.matches(regex);
    }

    public static void main(String[] args) {
        System.out.println(isValid("123-456-7890"));
    }

}

P.S. The regex pattern we use extra » for escaping when we use in java string. (Try to use «d{3}-d{3}-d{4}» in java program, you will get an error.

answered Nov 15, 2016 at 5:28

rohan's user avatar

rohanrohan

1112 silver badges3 bronze badges

Assuming you want an optimization (which is what your comment suggests).

How bout this? (the «0» is to exclude if they give complete garbage without even a single digit).

 int parse(String phone){
     int num = Integer.parseInt("0"+phone.replaceAll("[^0-9]",""));
     return 100000000<=num&&num<100000000000?num:-1;
 }

answered Dec 24, 2014 at 5:20

k_g's user avatar

k_gk_g

4,3042 gold badges24 silver badges40 bronze badges

I am not sure but removing the garbage characters parenthesis, spaces and hyphens, if you match with ^((+[1-9]?[0-9])|0)?[7-9][0-9]{9}$ , you may validate a mobile number

private static final String PHONE_NUMBER_GARBAGE_REGEX = "[()\s-]+";
private static final String PHONE_NUMBER_REGEX = "^((\+[1-9]?[0-9])|0)?[7-9][0-9]{9}$";
private static final Pattern PHONE_NUMBER_PATTERN = Pattern.compile(PHONE_NUMBER_REGEX);

public static boolean validatePhoneNumber(String phoneNumber) {
    return phoneNumber != null && PHONE_NUMBER_PATTERN.matcher(phoneNumber.replaceAll(PHONE_NUMBER_GARBAGE_REGEX, "")).matches();
}

answered Aug 25, 2016 at 0:32

Deepak's user avatar

DeepakDeepak

4914 silver badges10 bronze badges

One easy and simple to use java phone validation regex:

public static final String PHONE_VERIFICATION = "^[+0-9-\(\)\s]*{6,14}$";

private static Pattern p;
private static Matcher m;

public static void main(String[] args)
{
    //Phone validation
    p = Pattern.compile(PHONE_VERIFICATION);
    m = p.matcher("+1 212-788-8609");
    boolean isPhoneValid = m.matches();

    if(!isPhoneValid)
    {
        System.out.println("The Phone number is NOT valid!");
        return;
    }
    System.out.println("The Phone number is valid!");
}

answered Jun 21, 2017 at 10:59

Armer B.'s user avatar

Armer B.Armer B.

7032 gold badges8 silver badges25 bronze badges

i have done testing one regex for this combination of phone numbers

(294) 784-4554
(247) 784 4554
(124)-784 4783 
(124)-784-4783
(124) 784-4783
+1(202)555-0138

THIS REGEX SURELY WILL BE WORKING FOR ALL THE US NUMBERS

d{10}|(?:d{3}-){2}d{4}|(d{3})d{3}-?d{4}|(d{3})-d{3}-?d{4}|(d{3}) d{3} ?d{4}|(d{3})-d{3} ?d{4}|(d{3}) d{3}-?d{4}

answered Sep 20, 2017 at 11:31

Deepesh Jain's user avatar

Building on @k_g’s answers, but for US numbers.

static boolean isValidTelephoneNumber(String number) {
    long num = Long.parseLong("0" + number.replaceAll("[^0-9]", ""));
    return 2000000000L <= num && num < 19999999999L;
}

public static void main(String[] args) {
    var numbers = List.of("+1 212-788-8609", "212-788-8609", "1 212-788-8609", "12127888609", "2127888609",
            "7143788", "736103355");

    numbers.forEach(number -> {
        boolean isPhoneValid = isValidTelephoneNumber(number);
        log.debug(number + " matches = " + isPhoneValid);
    });
}

answered Aug 15, 2020 at 19:35

Jose Martinez's user avatar

Jose MartinezJose Martinez

11.2k7 gold badges53 silver badges65 bronze badges


This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters

Show hidden characters

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»);
}
}
}

In this article, we’ll learn how to validate mobile phone number of different country’s format using Java Regex (Regular Expressions)

Phone Number Format

A typical mobile phone number has following component:

+<country_code> <area_code> <subscriber_number>

Where depending on the country,

  • country_code is somewhere between 1 to 3 digits
  • area_code and subscriber_number combined is somewhere between 8 to 11 digits

If you simply require a regex to match all country format then here it is,

"^(\+\d{1,3}( )?)?((\(\d{1,3}\))|\d{1,3})[- .]?\d{3,4}[- .]?\d{4}$"

If you want to know **how we came up with this regex?** then please read this full article.

1. Regex to match 10 digit Phone Number with No space

This is simplest regex to match just 10 digits. We will also see here how to use regex to validate pattern:

String regex = "^\d{10}$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher("9876543210");
matcher.matches(); // returns true if pattern matches, else returns false

Let’s break the regex and understand,

  • ^ start of expression
  • d{10} is mandatory match of 10 digits without any space
  • $ end of expression

You can make regex more flexible to match between 8 to 11 digits phone number with no space, using this regex:

String noSpaceRegex = "^\d{8,11}$";

2. Regex to match 10 digit Phone Number with WhiteSpaces, Hyphens or No space

String spacesAndHyphenRegex = "^(\d{3}[- ]?){2}\d{4}$";

Let’s break the regex and understand,

  • ^ start of expression
  • d{3} is mandatory match of 3 digits
  • [- ]? is optional match of whitespace or hyphen after 3 digits
  • {2} is to repeat the above match d{3}[- ]? two times becomes total 6 digits
  • d{4} is mandatory match of last 4 digits
  • $ end of expression

This Pattern will match mobile phone numbers like 9876543210, 987 654 3210, 987-654-3210, 987 654-3210, 987 6543210, etc.

3. Regex to match 10 digit Phone Number with Parentheses

String parenthesesRegex = "^((\(\d{3}\))|\d{3})[- ]?\d{3}[- ]?\d{4}$";

Let’s break the regex and understand,

  • ^ start of expression
  • (\(\d{3}\))|\d{3}) is mandatory match of 3 digits with or without parentheses
  • [- ]? is optional match of whitespace or hyphen after after 3 digits
  • \d{3}[- ]? is mandatory match of next 3 digits followed by whitespace, hyphen or no space
  • \d{4} is mandatory match of last 4 digits
  • $ end of expression

This Pattern will match mobile phone numbers with spaces and hyphen, as well as numbers like (987)6543210, (987) 654-3210, (987)-654-3210 etc.

4. Regex to match 10 digit Phone number with Country Code Prefix

This regex is combined with regex to include parenthesis

String countryCodeRegex = "^(\+\d{1,3}( )?)?((\(\d{3}\))|\d{3})[- .]?\d{3}[- .]?\d{4}$";

Let’s break the regex and understand,

  • ^ start of expression
  • (\+\d{1,3}( )?)? is optional match of country code between 1 to 3 digits prefixed with + symbol, followed by space or no space.
  • ((\(\d{3}\))|\d{3})[- .]?\d{3}[- .]?\d{4} is mandatory match of 10 digits with or without parenthesis, followed by whitespace, hyphen or no space
  • $ end of expression

This Pattern will match mobile phone numbers from previous examples as well as numbers like +91 (987)6543210, +111 (987) 654-3210, +66 (987)-654-3210 etc.

5. Regex to match Phone Number of All Country Formats

Before we start defining a regex, let’s look at some of the country phone number formats:-

Abkhazia    +995 442 123456
Afghanistan +93 30 539-0605
Australia   +61 2 1255-3456
China       +86 (20) 1255-3456
Germany     +49 351 125-3456
Indonesia   +62 21 6539-0605
Iran        +98 (515) 539-0605
Italy       +39 06 5398-0605
New Zealand +64 3 539-0605
Philippines +63 35 539-0605
Singapore   +65 6396 0605
Thailand    +66 2 123 4567
UK          +44 141 222-3344
USA         +1 (212) 555-3456
Vietnam     +84 35 539-0605

Let’s extract some information from these numbers:-

  1. Country Code prefix starts with ‘+’ and has 1 to 3 digits
  2. Last part of the number, also known as subscriber number is 4 digits in all of the numbers
  3. Most of the countries have 10 digits phone number after excluding country code. A general observation is that all countries phone number falls somewhere between 8 to 11 digits after excluding country code.

Let’s see again on regex from previous example to validate country code:

String countryCodeRegex = "^(\+\d{1,3}( )?)?((\(\d{3}\))|\d{3})[- .]?\d{3}[- .]?\d{4}$"l

The above regex is to match 10 digit phone numbers, Let’s make some changes in this and make it more flexible to match 8 to 11 digits phone numbers:-

Regex to Match All Country Formats
String allCountryRegex = "^(\+\d{1,3}( )?)?((\(\d{1,3}\))|\d{1,3})[- .]?\d{3,4}[- .]?\d{4}$";

Let’s break the regex and understand,

  • ^ start of expression
  • (\+\d{1,3}( )?)? is optional match of country code between 1 to 3 digits prefixed with ‘+’ symbol, followed by space or no space.
  • ((\(\d{1,3}\))|\d{1,3} is mandatory group of 1 to 3 digits with or without parenthesis followed by hyphen, space or no space.
  • \d{3,4}[- .]? is mandatory group of 3 or 4 digits followed by hyphen, space or no space
  • \d{4} is mandatory group of last 4 digits
  • $ end of expression

6. Regex to match Phone Number of Specific Country Format

As you saw in the previous example that we have to add some flexibility in our regex to match all countries’ formats. If you want more strict validation of specific country format then here are examples of India and Singapore Phone number regex pattern:

String indiaRegex = "^(\+\d{2}( )?)?((\(\d{3}\))|\d{3})[- .]?\d{3}[- .]?\d{4}$";
String singaporeRegex = "^(\+\d{2}( )?)?\d{4}[- .]?\d{4}$";

In this post, we will see how to validate phone number in java.

Table of Contents

  • Validate any international phone number as per E.123
    • Regex
    • Explanation
  • Validate Indian mobile number
    • Regex
    • Explanation

Validate any international phone number as per E.123

E.123 is a standards-based recommendation by the International Telecommunications Union sector ITU-T.

E.123 provides following specifications.

  • The leading plus (+) serves as an international prefix symbol, and is immediately followed by the country code and then phone number.
  • Spaces should separate country code, area code and local number.

Regex

^+(?:[0-9] ?){6,14}[0-9]$

Explanation

^ –> Assert position at the beginning of the string.
+ –> Match a literal “+” character.
(?: –> Group but don’t capture:
[0-9] –> Match a digit from 0-9.
x20 –> Match a space character(used x20 to show space character)
? –> between zero and one time.
) –> End the noncapturing group.
{6,14} –> Recur the group between 6 and 14 times.
[0-9] –> Match digit from 0-9
$ –> Assert position at the end of the string.

Java program to check phone number

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

package org.arpit.java2blog;

// Java program to check phone

// is valid as per E123

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class ValidatePhoneNumberMain {

    public static boolean isValidE123(String s)

    {

        Pattern p = Pattern.compile(«^\+(?:[0-9] ?){6,14}[0-9]$»);

        Matcher m = p.matcher(s);

        return (m.find() && m.group().equals(s));

    }

    public static void main(String[] args)

    {

        String phone1 = «+91 3423 546443»;

        String phone2 = «+44 343 2324»;

        String phone3 = «91 4354 3454»;

        String[] phoneNumbers= {phone1,phone2,phone3};

        for (int i = 0; i < phoneNumbers.length; i++) {

            String phoneNumber=phoneNumbers[i];

            if (isValidE123(phoneNumber))

                System.out.print(phoneNumber+» is valid phone number»);

            else

                System.out.print(phoneNumber+» is invalid Phone number»);

            System.out.println();

        }    

    }

}

Output

+91 3423 546443 is valid phone number
+44 343 2324 is valid phone number
91 4354 3454 is invalid Phone number

Validate Indian mobile number

Valid indian mobile numbers are:

9876543210
09876543210
919876543210
0919876543210
+919876543210
+91-9876543210
0091-9876543210
+91 -9876543210
+91- 9876543210
+91 – 9876543210
0091 – 9876543210

Regex

^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$

Explanation

I would recommend to go to site https://regex101.com/. Put the regex in regular expression. It will show you clear explanation of regex.
Here is java program for the validate indian mobile number

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

package org.arpit.java2blog;

// Java program to check phone

// is valid as per E123

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class ValidatePhoneNumberMain {

    public static boolean isValidIndianMobileNumber(String s)

    {

        Pattern p = Pattern.compile(«^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$»);

        Matcher m = p.matcher(s);

        return (m.find() && m.group().equals(s));

    }

    public static void main(String[] args)

    {

        String phone1 = «+91-7123456789»;

        String phone2 = «08123456789»;

        String phone3 = «9876543210»;

        String[] phoneNumbers= {phone1,phone2,phone3};

        for (int i = 0; i < phoneNumbers.length; i++) {

            String phoneNumber=phoneNumbers[i];

            if (isValidIndianMobileNumber(phoneNumber))

                System.out.print(phoneNumber+» is valid mobile number»);

            else

                System.out.print(phoneNumber+» is invalid mobile number»);

            System.out.println();

        }    

    }

}

Output

+91-7123456789 is valid mobile number
08123456789 is valid mobile number
9876543210 is valid mobile number

That’s all about validate phone number in java.

Regular Expressions (RegEx) are a powerful tool and help us match patterns in a flexible, dynamic and efficient way, as well as to perform operations based on the results.

In this tutorial, we’ll take a look at how to validate an phone number in Java, using Regular Expressions (RegEx).

If you’d like to read more about Regular Expressions and the regex package, read out Guide to Regular Expressions in Java!

Validating Phone Numbers in Java with RegEx

Phone numbers aren’t easy to validate, and they’re notoriously flexible. Different countries have different formats, and some countries even use multiple formats and country codes.

To validate a phone number with Regular Expressions, you’ll have to make a couple of assertions that generalize well to phone numbers, unless you want to write many different expressions and validate through a list of them.

These assertions will depend on your project, its localization and the countries you wish to apply it to — but keep in mind that with an international project, you might have to be loose on the restrictions lest you end up not allowing a valid phone number through to the system.

For standard US phone number validation, we can use the lengthy, fairly robust expression of:

^(+d{1,2}s)?(?d{3})?[s.-]?d{3}[s.-]?d{4}$

The 4 groups in the expression correspond to the country code, area number, subscriber number and extension. The expressions in-between the groups are there to handle a wide-variety of different formatting you an see:

123-456-7890
(123) 456-7890
etc...

You could also build a different expression by imposing a set of rules for groups (depending on the country) and the formats. you may expect coming in.

You could technically go as simple as checking whether there’s 10 numbers in the string (12 if you count the country code as well), and it should be able to validate some of the phone numbers, but such simplicity would require additional validation either on the front-end, or the ability to adapt if an accepted phone number isn’t actually valid:

Pattern simplePattern = Pattern.compile("^\+\d{10,12}$");
Pattern robustPattern = Pattern.compile("^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$");

String phoneNumber = "+12 345 678 9012";

Matcher simpleMatcher = simplePattern.matcher(phoneNumber);
Matcher robustMatcher = robustPattern.matcher(phoneNumber);

if (simpleMatcher.matches()) {
    System.out.println(String.format("Simple Pattern matched for string: %s", phoneNumber));
}
if(robustMatcher.matches()) {
    System.out.println(String.format("Robust Pattern matched for string: %s", phoneNumber));
}

The first matcher, here, will first and foremost have issues with the whitespaces present in the string, and would match otherwise. The robust pattern doesn’t have any issues with this, though:

Robust Pattern matched for string: +12 345 678 9012

The robust matcher here would be able to match for several formats:

Pattern robustPattern = Pattern.compile("^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$");

List<String> phoneNumbers = List.of(
        "+12 345 678 9012",
        "+123456789012",
        "345.678.9012",
        "345 678 9012"
);

for (String number : phoneNumbers) {
    Matcher matcher = robustPattern.matcher(number);
    if(matcher.matches()) {
        System.out.println(String.format("Robust Pattern matched for string: %s", number));
    }
}

This would result in:

Robust Pattern matched for string: +12 345 678 9012
Robust Pattern matched for string: 345.678.9012
Robust Pattern matched for string: 345 678 9012

Combining Multiple Regular Expressions

Regular Expressions tend to get messy and long. At a certain point, they become cluttered enough that you can’t readily change them or interpret them.

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Instead of having a single, universal, robust Regular Expression that encompasses all edge-cases, countries, etc. — you can opt to use several different patterns that will reasonably cover the phone numbers coming in. To make things simpler — you can chain these expressions via the | operator, to check whether the phone number matches any of the patterns:

Pattern robustPattern = Pattern
        .compile(
                // Robust expression from before
                "^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$"
                // Area code, within or without parentheses,
                // followed by groups of 3-4 numbers with or without hyphens
                + "| ((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}"
                // (+) followed by 10-12 numbers
                + "|^\+\d{10,12}"
);

List<String> phoneNumbers = List.of(
        "+12 345 678 9012",
        "+123456789012",
        "345.678.9012",
        "345 678 9012"
);

for (String number : phoneNumbers) {
    Matcher matcher = robustPattern.matcher(number);
    if(matcher.matches()) {
        System.out.println(String.format("Pattern matched for string: %s", number));
    }
}

This results in:

Pattern matched for string: +12 345 678 9012
Pattern matched for string: +123456789012
Pattern matched for string: 345.678.9012
Pattern matched for string: 345 678 9012

Conclusion

Phone numbers are tricky — that’s a fact. Regular Expressions are a really versatile and powerful tool and can address the issue of validating phone numbers, but it is admittedly a messy process.

Certain countries follow different standards, while some countries adopt and use multiple formats at the same time, making it hard to write a general-purpose expression to match phone numbers universally.

In this short article, we’ve taken a look at how to match phone numbers with Regular Expressions in Java, with a few different expressions.

Как проверить номер телефона в Java (регулярное выражение)

Шаблон регулярных выражений в Java всегда является лучшим методом для проверки номера телефона пользователя. Здесь я предоставляю шаблон регулярного выражения, чтобы определить, находится ли номер телефона в правильном формате, шаблонforce starting with 3 digits follow by a “-” and 7 digits at the end.

Explanation
d = разрешить только цифру
{3} = длина

Все телефонные номера должны быть в формате «xxx-xxxxxxx». Например,
1) 012-6677889 — Пройдено
2) 01216677889 — Не выполнено, «-» отсутствует
3) A12-6677889 — Не выполнено, разрешены только цифры
4) 012-66778899 — Ошибка, только 7 цифр в конце

Полный исходный код проверки номера телефона на Java

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

public class ValidatePhoneNumber {
  public static void main(String[] argv) {

      String sPhoneNumber = "605-8889999";
      //String sPhoneNumber = "605-88899991";
      //String sPhoneNumber = "605-888999A";

      Pattern pattern = Pattern.compile("\d{3}-\d{7}");
      Matcher matcher = pattern.matcher(sPhoneNumber);

      if (matcher.matches()) {
          System.out.println("Phone Number Valid");
      }
      else
      {
          System.out.println("Phone Number must be in the form XXX-XXXXXXX");
      }
 }
}

Понравилась статья? Поделить с друзьями:
  • Валео партизанск номер телефона
  • Валео вита нальчик номер телефона
  • Валентина чупик правозащитник номер телефона
  • Валенти ленинск кузнецкий номер телефона
  • Валента кабельное костанай номер телефона