Java Program to Check For a Valid Mobile Number
Regular Expressions or Regex (in short) is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are few areas of strings where Regex is widely used to define the constraints. Regular Expressions are provided under java.util.regex package. This consists of 3 classes and 1 interface.
Here we will be discussing out two examples, one for India and the other be standard validating over for all countries. Hence, the cases are as follows:
- Case 1: Local phone numbers that are Indian phone numbers
- Case 2: Global phone numbers
Case 1: Local phone numbers that are Indian phone numbers
Mobile Number validation criteria are as follows:
- The first digit should contain numbers between 7 and 9.
- The rest 9 digits can contain any number between 0 and 9.
- The mobile number can have 11 digits also by including 0 at the starting.
- The mobile number can be of 12 digits also by including 91 at the starting.
Input : Enter Mobile Number: 7873923408 Output : Valid Mobile Number
Input : Enter Mobile Number: 5678729234 Output : Invalid Mobile Number
One must have a good understanding of regular expression as it is a prerequisite. Mobile number validation in Java is done using Pattern and Matcher classes of Java. The pattern class is used to compile the given pattern/regular expression and the matcher class is used to match the input string with compiled pattern/regular expression. In this method, a regular expression is mentioned, which mentions the criteria for validation of the input string which in this article is a mobile number. The mobile number in India has 10 digits, so we can mention a regular expression that contains only 10 digits.
Valid Number Invalid Number
Case 2: Global phone numbers
The approach is again with the help of regular Expression to match Phone Number of All Country Formats
Mobile number validation criteria:
- The country code prefix starts with ‘+’ and has 1-3 digits.
- Most of the countries have the last 4 digits after a hyphen(-).
The numbers which satisfy the validation are shown in illustrations as follows:
Input : Enter Mobile Number : +1 212 555-3458 (USA) Output : Valid Mobile Number
Input : Enter Mobile Number : +4934 351 125-3456 Output : Invalid Mobile Number
Valid Number Invalid Number
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.