Sunday 9 February 2014

Regular Expression for Indian Mobile Numbers.

Recently I was developing website using ASP.NET MVC 4 and wanted to add validation to my form to validate Indian mobile number. I wanted it to validate numbers entered in following format as valid!

1. It can be 10 digit number with first digit should be either 7,8 or 9
2. It can precede with a digit 0 or +91 or 0091. This is optional.

Below is sample code snippet showing the regular expression used to validate Indian Mobile Number.

         // Below is sample code snippet.
            function bool IsValidMobileNumber(string mobileNumber){
           string pattern = @"^((0091)|(\+91)|0?)[789]{1}\d{9}$";
            Regex regMobile = new Regex(pattern);
            return regMobile.IsMatch(mobileNumber);
           }


You can decorate the Model value as below when using it in ASP,NET MVC,
//This is required to annotate the public property of model.
using System,ComponentModel.DataAnnotations;


public class    SomeModel {

  [RegularExpression(@"^((0091)|(\+91)|0?)[789]{1}\d{9}$", ErrorMessage = "Mobile Number is not valid!")]
        public string MobileNumber get;set;


}
Here is an interpretation of this Regular Expression.

  • ^ and $ are anchor tags and indicate start and end of expression to be matched.
  • We want three groups to be used either 0091,+91 or 0  and hence the group are specified in () brackets with '|' character to indicate or logic  '?' indicate it is optional.
  • I wanted 7,8 or 9  as first digit of 10 digit mobile number so [789]{1} indicate only valid digits in rectangular bracket and curly braces indicate I want it to be exact one digit long.
  • Please note '+' has special meaning in regular expression and need to be preceded with '\' character if it is to be used as normal character and hence (\+91) 
  • '\d{9}' indicate allow only valid digits 0 to 9 and should be 9 digits long.
I have tested it with different valid combinations and it works fine.
e.g. of valid numbers are given below.
  •   00919123456789
  • +0917123456789
  • 09123456789
  • 7123456780
  • 8012345678
  • 9012345678

I hope you will find this useful!





No comments:

Post a Comment