Skip to content

Java RegEx – 10 Digit Mobile Number Validation

The Java RegEx – 10 Digit Mobile Number Validation example shows how to validate a 10 digit mobile number using Java regular expression. It also shows how to validate an 11 digit number having 0 at the start.

How to validate a 10 digit mobile number using a Java regex pattern?

The mobile phone number syntax is fairly simple, at least in India. It should contain all digits and the length must be 10. So basically we want to validate that the input phone number does not have anything except digits 0-9 and the number length must be 10.

Here is the simple pattern to validate this.

Where,

Let’s test the pattern with some sample phone numbers.

Output

The first number is 11 digits so it fails the validation. The second number is 9 in length, so it fails too. The third number contains the character “a” which is not allowed in the phone number, so it fails. The fourth number is validated successfully.

Our pattern worked for the regular numbers but what about the mobile number “0123456789”? The length of the number is 10 and it only contains digits, so it should be validated using our pattern. However, this number is not valid because it has a leading 0 so basically, it is only 9 digits in length.

Output

To fix this, we can modify our pattern a little bit like given below.

This pattern forces the first digit to be non-zero. The rest of the 9 digits can be anything from 0 to 9.

Final code:

Output

The first and second number is not 10 in length so both of them fails the validation. The third number contains an alphabet that is not allowed in the mobile number, so it fails as well. The fourth number is 10 in length but starts with a 0, so it fails as well.

RegEx Validation for 11 digits with a leading 0

Some countries allow an additional 0 at the start of the number. For example, in India, we can prepend 0 to any mobile number. In that case, the first digit is “0”, the second digit must be between 1 to 9 and the rest of the 9 digits can be anything from 0 to 9.

Since the starting 0 is optional, we also need to accommodate the 10 digit regular mobile numbers and 11 digit mobile numbers with a leading 0. For this requirement, the pattern could be written as given below.

I have combined two patterns using the “|” (or condition). Here are some of the mobile number validations using this pattern.

This example is part of Java Regular Expression Tutorial with Examples.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.