How to Validate Indian Phone Number


You need to validate your phone number according to specified format. But how? So here is the right code for you.

How To Validate Indian Phone Number



Concepts Used:


1. Namespace: System.Text.RegularExpressions for pattern creation and matching.
2. KeyPress event of TextBox to check characters by KeyChar property.
3. Calling event handler of Check button from Textbox KeyPress event handler.

Code Snippet:



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions; //namespace to be used to match patterns

namespace dsn_PhoneNumberValidation
{
public partial class Form1 : Form
{
//Defining a regular expression and pattern
Regex phoneRegex = new Regex("^\\+[9][1][-][\\d]{10}$");

public Form1()
{
InitializeComponent();
}

private void btnCheck_Click(object sender, EventArgs e)
{
string strPhone = txtPhone.Text;

Match getMatch = phoneRegex.Match(strPhone);

if (getMatch.Success)
{
lblInfo.ForeColor = System.Drawing.Color.Blue;
lblInfo.Text = "MESSAGE: Absolutely correct phone number!";
}
else
{
lblInfo.ForeColor = System.Drawing.Color.Red;
lblInfo.Text = "MESSAGE: Wrong phone number.Phone number \nshould be 10 digit and format as +91-1234567890.";
}

}

private void txtPhone_KeyPress(object sender, KeyPressEventArgs e)
{
if (txtPhone.Text != String.Empty)
{
//KeyChar(45) for hypen key
//KeyChar(13) for Enter key
//KeyChar(8) for Backspace key
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 45 && e.KeyChar!=13)
{
lblInfo.ForeColor = System.Drawing.Color.Red;
lblInfo.Text = "ONLY DIGITS ALLOWED. LETTERS NOT PERMITTED!";
}
else
{
lblInfo.Text=String.Empty;
}
}

//Calling btnCheck_Click event handler on Enter key pressed
if (e.KeyChar == 13)
{
btnCheck_Click(this, EventArgs.Empty);
}
}
}
}


Regular Expression Pattern Explained:

^\\+[9][1][-][\\d]{10}$

^ - Front anchor
\\+ - For checking + in begining of phone number
[9] - Next number should be 9 only
[1] - Next number should be 1 only
[\\d] - Later there should be digits only
{10} - Digits should be ten in numbers
$ - Ending anchor


Attachments

  • phoneNumberValid (37635-11638-dsn_PhoneNumberValidation.rar)
  • Comments



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: