PrettyPrint

Searching...
Tuesday 15 April 2014

check given mobile number is valid or not in java using regex

16:58
mobile-validation

In this post we will see how to identiy whether given mobile number is valid or not. May be you have come across the situation to check mobile number is valid or not if yes than here is the solution :

Our Requirements :

1. If number starts with "0" than remove "0" and return 10 digit mobile number.
2. If number starts with "+91" than remove "+91" and return 10 digit mobile number.
3. Finally, check this 10 digit mobile number is matches with given series of numbers or not.

step 1 : Check number starts with "0" or not
    String mobNo="09975225406";
    //checking whether mobile number starts with "0"
    if(mobNo.startsWith("0"))
        mobNo=mobNo.substring(0, mobNo.length());

Step 2 : Check number starts with "+91" or not
    String mobNo="+919975225406";
    //checking whether mobile number starts with "+91"
    if(mobNo.startsWith("+"))
        mobNo=mobNo.substring(3, mobNo.length());

Step 3 : check whether matches with regex pattern or not
    //this regex will check starting 4 digits of 10 digit mobile number
    String regex="^(?:9867|9975|9989)[0-9]{6}$";
    if(mobNo.matches(regex))
        {
            System.out.println("valid mobile number");
        }

Complete code as given below :

public class MobValidation {
 
 public static void main(String[] args) {
  
  String mobNo="+919975225406";
  String regex="^(?:9867|9975|9989)[0-9]{6}$";
  
  //checking whether mobile number starts with "0"
  if(mobNo.startsWith("0"))
   mobNo=mobNo.substring(0, mobNo.length());
  //checking whether mobile number starts with "+91"
  else if(mobNo.startsWith("+"))
   mobNo=mobNo.substring(3, mobNo.length());
  if(mobNo.matches(regex))
  {
   System.out.println("valid mobile number");
  }
  else
  {
   System.out.println("invalid mobile number");
  }
 }
}
NOTE : The above code works only on mobile numbers that starts with "0" or "+91" or exact 10 digit mobile number and starts with 9867 or 9975 or 9989 e.g : +919975225406, 09975225406, 9975225406, 9867112235, +919867112235, 09867112235

Next
This is the most recent post.
Previous
This is the last post.

1 comments:

  1. Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info. Modern Behaviour Pty Ltd

    ReplyDelete