Validations using Regular Expressions
Validations using Regular Expressions:
Description:
The below code is used to Validate data using regular expressions.Design View:
< form id="form1" runat="server" >
< div >
< fieldset style="width:50%" >
< legend > Finding Number using RegularExpressions < /legend >
< table >
< tr >
< td > String containing Number: < asp:TextBox ID="txtText" runat="server" > < /asp:TextBox > < /td >
< /tr >
< tr >
< td > < asp:Button ID="btnFind" Text="Find Number" runat="server" onclick="btnFind_Click" /> </td >
</tr >
< tr >
< td > < asp:Label ID="lblResults" runat="server" > < /asp:Label > < /td >
< /tr >
< /table >
< /fieldset >
< fieldset style="width:50%" >
< legend > Validations using RegularExpressions </legend >
< table >
< tr >
< td > Zip Code: < asp:TextBox ID="txtZipCode" runat="server" > </asp:TextBox > (A 5-digit or 5+4 digit zip code.)
< /td >
< /tr >
< tr >
< td > Date: < asp:TextBox ID="txtDate" runat="server" > < /asp:TextBox > (Date in mm-dd-yyyy or mm-dd-yy format) < /td >
< /tr >
< tr >
< td > Email: < asp:TextBox ID="txtEmail" runat="server" > </asp:TextBox> </td >
< /tr >
< tr >
< td > < asp:Button ID="btnValidate" Text="Validate" runat="server"
onclick="btnValidate_Click"/> </td >
< /tr>
< tr >
< td > < asp:Label ID="lblValidate" runat="server" > </asp:Label > </td >
< /tr >
< /table >
< /fieldset >
< /div >
< /form >Code Behind:
using System.Text.RegularExpressions;
protected void btnFind_Click(object sender, EventArgs e)
{
Match mtch = Regex.Match(txtText.Text, @"\d+");
if (mtch.Success)
{
//It will find the number's position in the given string ex:abc123abc - it finds 1 at 3rd position
lblResults.Text = string.Format("RegEx found " + mtch.Value + " at position " + mtch.Index.ToString());
}
else
{
lblResults.Text = "You didn't enter a string containing a number!";
}
}
protected void btnValidate_Click(object sender, EventArgs e)
{
bool IsValid = true;
// Zip Code validation
if (!Regex.IsMatch(txtZipCode.Text, @"^\s*(\d{5}|(\d{5}-\d{4}))\s*$"))
{
txtZipCode.ForeColor = Color.Red;
IsValid = false;
}
else
{
txtZipCode.ForeColor = Color.Black;
}
//Date validation
if (!Regex.IsMatch(txtDate.Text, @"^\s*\d{1,2}(/|-)\d{1,2}\1(\d{4}|\d{2})\s*$"))
{
txtDate.ForeColor = Color.Red;
IsValid = false;
}
else
{
txtDate.ForeColor = Color.Black;
}
// email validation
if (!Regex.IsMatch(txtEmail.Text, @"^([\w-]+\.)*?[\w-]+@[\w-]+\.([\w-]+\.)*?[\w]+$"))
{
txtEmail.ForeColor = Color.Red;
IsValid = false;
}
else
{
txtEmail.ForeColor = Color.Black;
}
}
try this link:
http://www.manindra.net/post/2010/04/09/AspNet-Regular-Expressions.aspx