Powered by Blogger.

Tuesday, February 18, 2014

RegularExpressionValidator example in Asp.Net



In this post we will discuss how to use RegularExpressionValidator in Asp.Net. For this example we will see how to validate email id using RegularExpressionValidator in Asp.Net.

You can also check examples of RangeValidator and RequiredFieldValidator in Asp.Net.

- RegularExpressionValidator: Here validation succeeds if the value in an input control matches a specified regular expression.

Below are the properties:
ControlToValidate: Which control you want to validate.

ErrorMessage: What error message you want to show.

ValidationExpression: This represents the validation expression you want to validate. You can directly set the validation expression or Asp.Net provides some validation expressions which you can select from RegularExpressionValidator's properties window.

Below is the full HTML code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ValidatorExamples.aspx.cs"
    Inherits="ValidatorExamples" %>

<!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 id="Head1" runat="server">
    <title>RegularExpressionValidator example in Asp.Net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Enter EmailID:<asp:TextBox ID="txtEmailID" runat="server"></asp:TextBox>
        <br />
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ForeColor="Red"
            ControlToValidate="txtEmailID" ErrorMessage="Please enter a valid email id" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
        <br />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
    </div>
    </form>
</body>

</html>

If a user enters a invalid email id then the error will be shown as shown in the figure below:






0 comments

Post a Comment