Speed up development with full-stack environments for every branch.

Learn More

How to do Validation in ASP.NET

3946 Runs 28459 Views 3500 Copies
Saved

Saved

mirang 126

mirang
published 4 years ago

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Collections.Generic" %>
<!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> 
   <title>How to do Validation in ASP.NET</title>
    <script language="C#" runat="server">
        public void Page_Load(Object sender, EventArgs e)
        {
            //Print the time when the page loaded initially
            Response.Write("The Page Loaded at: " + DateTime.Now.ToLongTimeString());

            //Attach the server validate event so that the custom validation can be done on the server
            cvUserExist.ServerValidate += new ServerValidateEventHandler(cvUserExist_ServerValidate);
        }

        //Method that will be called, when the form is submitted. Here the custom validation will be done like checking the value in the database etc..
        void cvUserExist_ServerValidate(object source, ServerValidateEventArgs args)
        {
            //this is just hard code to check against [email protected],
            //but in real world scenerio, it would be like a database lookup, to check the availability of the email address
            if (txtEmail.Text == "[email protected]")
            {
                //to invalidate the value entered by the user, set the args.IsValid = false
                args.IsValid = false;
            }
            else
            {
                //to validate the value entered by teh user, set teh args.IsValid = true
                args.IsValid = true;
            }
        }
    </script>
    
    <style type="text/css">
    .button
    {
      border-radius:4px 4px 4px 4px;
      height:30px;
      padding:5px;
      font-size:14px;
      background-color:#6ca21e;
      color:#FFFFFF
    }
    #divServerTime
    {
      width:100px;
      height:30px;
      font-weight:bold;
      float:left;
      font-size:20px;
      margin-left:10px;
    }
    body
    {
      background-color:#32373a;
      color:#FFFFFF;
    }
    #mainBody
    {
      background-color:#FFFFFF;
      height:800px;
      color:#32373a;
    }
    .divMainTime
    {
      width:450px;
      height:30px;
      background-color:#fdd136;
      font-size:14px;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    
    <div id='mainBody'>
    <h1>
        How to do Validation in ASP.NET
    </h1>
        
    <br />
        <!--
        ValidationSummary gives a summary of all the errors on the page, which failed validation, Properties to be set
        DisplayMode is the mode to display the errors
         -->
        <asp:ValidationSummary DisplayMode="BulletList" runat="server" />
        <br />
        <div style="width:500px;background-color:#fdd136">
            <b>Required Field Validator </b>- Makes sure that the required field is not empty.
        </div>
        <br />
        <asp:TextBox ID="txtFullName" runat="server" />
        <!-- For RequiredFieldValidator properties required to be set, 
        - ControlToValidate which will be the control on which the validation has to be done,
        - ErrorMessage that will be displayed when the validation fails
        - SetFocusOnError will set focus on that control when error occurs
        -->
        <asp:RequiredFieldValidator ID="rfvFullName" runat="server" ControlToValidate="txtFullName" ErrorMessage="Please enter your Full Name" SetFocusOnError="true" />
        <br /><br /><hr />
        <div style="width:500px;background-color:#fdd136">
            <b>Range Validator </b>- Makes sure that the value falls within a predefined range.
        </div>
        <br />
        <asp:TextBox ID="txtAge" runat="server" />
        <!-- For RangeValidator properties required to be set, 
        - ControlToValidate which will be the control on which the validation has to be done,
        - ErrorMessage that will be displayed when the validation fails
        - Type that will be the data type for which you want to perform the range validation
        - Mi
        - SetFocusOnError will set focus on that control when error occurs
        -->
        <asp:RangeValidator ID="rvAge" runat="server" ControlToValidate="txtAge" Type="Integer" MinimumValue="18" MaximumValue="60" ErrorMessage="Age should be between 18 and 60 years" SetFocusOnError="true" />
        <br /><br /><hr />
        <div style="width:500px;background-color:#fdd136">
            <b>Compare Validator </b>- Compares value in one control with a fixed value or some another control
        </div>
        <br />
        <asp:TextBox ID="txtYear" runat="server" />
        <!-- For CompareValidator properties required to be set, 
        - ControlToValidate which will be the control on which the validation has to be done,
        - ErrorMessage that will be displayed when the validation fails
        - ValueToCompare that will be the value against which the value of the control will be validated
        - Operator will be the operator for performing the comparison, you can also select datatypecheck in the Operator to perform the datatype check
        - SetFocusOnError will set focus on that control when error occurs
        -->
        <asp:CompareValidator ID="cvYear" runat="server" ControlToValidate="txtYear" Type="Integer" ValueToCompare="2000" Operator="GreaterThan" ErrorMessage="Year should be greater than 2000" SetFocusOnError="true" />

        <br /><br /><hr />

        <div style="width:500px;background-color:#fdd136">
            <b>RegularExpression Validator </b>- Provides a custom logic for validation against a regular expression
        </div>
        <br />
        <asp:TextBox ID="txtUrl" runat="server" />
        <!-- For RegularExpression Validator properties required to be set, 
        - ControlToValidate which will be the control on which the validation has to be done,
        - ErrorMessage that will be displayed when the validation fails
        - ValueToCompare that will be the value against which the value of the control will be validated
        - Operator will be the operator for performing the comparison, you can also select datatypecheck in the Operator to perform the datatype check
        - SetFocusOnError will set focus on that control when error occurs
        -->
        <asp:RegularExpressionValidator ID="revURL" runat="server" ControlToValidate="txtUrl" ErrorMessage="Url is not proper" ValidationExpression="^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$" SetFocusOnError="true" />
        <br /><br /><hr />

        <div style="width:500px;background-color:#fdd136">
            <b>Custom Validator </b>- Provides a custom logic for validation
        </div>
        <br />
        <asp:TextBox ID="txtEmail" runat="server" />
        <!-- For CustomValidator properties required to be set, 
        - ControlToValidate which will be the control on which the validation has to be done,
        - ErrorMessage that will be displayed when the validation fails
        - ValueToCompare that will be the value against which the value of the control will be validated
        - Operator will be the operator for performing the comparison, you can also select datatypecheck in the Operator to perform the datatype check
        - SetFocusOnError will set focus on that control when error occurs
        -->
        <asp:CustomValidator ID="cvUserExist" runat="server" ControlToValidate="txtEmail" ErrorMessage="This Email already exists" SetFocusOnError="true" />
        <br /><br /><br />
        <asp:Button ID="btnValidate" CssClass="button" Text="Validate" runat="server" />
        
    </div>
    </form>
</body>
</html>



Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).