Using the Regex Class ASP.Net

If you are not using server controls & validation controls or if you need to validate input from sources other than form fields, such as query string parameters or cookies, you can use the Regex class within the System.Text.RegularExpressions namespace.

To use the Regex class

1. Add a using statement to reference the System.Text.RegularExpressions namespace.
2. Call the IsMatch method of the Regex class, as shown in the following example.

// Instance method:
Regex reg = new Regex(@"^[a-zA-Z'.]{1,40}$");
Response.Write(reg.IsMatch(CusNameTxt.Text));

// Static method:
if (!Regex.IsMatch(CusNameTxt.Text,
@"^[a-zA-Z'.]{1,40}$"))
{
// Name does not match schema
}


Use the static IsMatch method where possible to avoid unnecessary object creation.

The following example shows how to use a regular expression to validate a name input through a regular client-side HTML control.

<%@ Page Language="C#" %>

<html >
<body>
<form id="form1" method="post" action="HtmlControls.aspx">
Name:
<input name="CusNameTxt" type="text" />
<input name="submitBtn" type="Submit" value="Submit"/>
</form>
</body>
</html>

<script runat="server">

void Page_Load(object sender, EventArgs e)
{
if (Request.RequestType == "POST")
{
string name = Request.Form["CusNameTxt"];
if (name.Length > 0)
{
if (System.Text.RegularExpressions.Regex.IsMatch(name,
"^[a-zA-Z'.]{1,40}$"))
Response.Write("Valid customer name");
else
Response.Write("Invalid customer name");
}
}
}

</script>
Tags: , , , ,
Hot on Web:


About author