Banner Ad

Wednesday, January 23, 2013

Validators in ASP.Net – Part 4 : Regular Expression Validator

By Francis   Posted at   11:15 AM   Validators in ASP.Net No comments

Regular Expression Validator:
                  In my previous posts, I have covered about 3 types of validators. In some situations the above 3 validators are helpful till some extend. Such that they may provide the flexibility to cover basic validation functionality. Regular Expression validator provide a step ahead functionality. 
                 For example if you want to validate to check the text box, to accept a valid Email address or phone no in a particular format at these times Regular Expression validator comes to picture.
                As its name implies, it uses Regular expressions to do validation.  This validator control also had same attributes like other with some other unique attributes, which  has been listed below.



Add a new web form and add the below code, when the wrong email id entered it will be thrown an error message. 



<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="RegularExpressionValidator.aspx.vb"
    Inherits="AllInOne.RegularExpressionValidator" %>

<!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>
        <table>
            <tr>
                <td>
                    <asp:Label ID="lblEmail" runat="server" Text="Enter Email"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:RegularExpressionValidator ID="valReg" runat="server" EnableClientScript="true"
                        ControlToValidate="txtEmail" ValidationExpression="w+([-+.']w+)*@w+([-.]w+)*.w+([-.]w+)*" 
                        ErrorMessage="Enter valid Email Address"></asp:RegularExpressionValidator>
                </td>
            </tr>
            <tr>
                <td colspan="3">
                    <asp:Button runat="server" ID="btnSubmit" Text="Submit" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Note:
                In this example we are just checking that the text box contains a valid format of email id, we didn’t check this email id exist actually. Which can be only checked in Mail Server.

Output:


Happy Programming
 

About Francis

Francis, an Associate at Cognizant. Having 7+ Years of experience in Microsoft web technologies.

0 comments :

Please give your valuable comments to improve the contents

Connect with Us