C# has provided
Regex
class for pattern matching and verifications.
Regex
class requires
System.Text.RegularExpressions
system namespace.
The foll. code demonstrates how to validate a mobile number (Indian) using C# Code Behind File.
HTML Front-End Code is: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MobileNumberVerification._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Enter Your Mobile Number: "></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Validate Number" OnClick="Button1_Click" />
<br />
<br />
<br />
<asp:Label ID="Label2" runat="server" Text="Valid Mobile Number"></asp:Label>
<br />
<br />
<asp:Label ID="Label3" runat="server" Text="Invalid Mobile Number"></asp:Label>
</div>
</form>
</body>
</html>
Code Behind File is: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MobileNumberVerification
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label2.Visible = false;
Label3.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
string patternForMobile = @"^\d{10}$";
Regex rgx = new Regex(patternForMobile, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(TextBox1.Text);
if (matches.Count > 0)
{
Label2.Visible = true;
Label3.Visible = false;
}
else
{
Label3.Visible = true;
Label2.Visible = false;
}
}
}
}
Code-Behind Justification:
Regex rgx = new Regex(patternForMobile, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(TextBox1.Text);
We are first creating
Regex
class object and then
MatchCollection
class to get the matches !!!