ASP.NET Tutorial

.NET Framework

ASP.NET Introduction

ASP.NET Web Forms

Standard Controls

Label Control

TextBox Control

Image Control

Button Controls

Redirecting User

Using HyperLinks

RadioButton Control

RadioButtonList

CheckBox Control

CheckBoxList Control

DropDownList

ListBox Control

ImageMap Control

Event-Driven Programming

ASP.NET Page Structure

IsPostBack

Master Page

View State

Visibility of Controls

Formatting Controls

Applying CSS

Dynamic CSS

Using Style Class

Themes and Skins

Panel Control

PlaceHolder Control

AdRotator Control

Calendar Control

File Upload, Virtual Path

Validation Controls

Page Navigation

User Control

Separating Code-Presentation

Overview of ADO.NET

Data Binding

DataBinding List Control

Asp.Net Validation Controls

The data entered by the user in a user registration form needs to be checked to see that the user name is unique, the user satisfies the criteria for accessing the resources on that site and finally to enter the user data in a database on the server. Some users may fill the data incorrectly or submit incomplete forms. The site administrator must verify that forms are filled completely and correctly. This is where validation of user input becomes a vital necessity.

Client-Side Validation Vs. Server-Side Validation

Client-side logic has to be browser-specific though it is faster, more scalable and does not load the network on the server. Many browsers support style sheets and DHTML, which enable page content to be changed dynamically.

Performing the validation on the server-side removes the need to cater to different browsers but introduces delay in response, loads the server, reduces scalability, and increases network traffic.

ASP.NET Client-Side Validation: ASP.NET provides six validation controls for validating user data. These are:

  • RequiredFieldValidator
  • CompareValidator
  • RangeValidator
  • RegularExpressionValidator
  • CustomValidator
  • ValidationSummary

For Validation controls use must add the following code in web.config file

<appSettings>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="none" />
</appSettings>

RequiredFieldValidator Control: This control is used to check that the user has entered a value in a mandatory field or not.

RequiredFieldValidator properties are listed in a table.
Property Description
ControlToValidate Specifies the ID of the control to be validated.
Display Sets how the error message contained in the Text property is displayed. Static (default), Dynamic, None.
EnableClientScript Enables or disables client-side form validation. By default, True.
Enabled Enables or disables both server and client-side form validation. By default, True.
ErrorMessage Specifies the error message that is displayed in the ValidationSummary control. It is displayed by the validation control when the Text property is not set.
InitialValue Gets or sets the initial value of the control being validated.
IsValid Is True when the validation check succeeds.
Text Sets the error message displayed by the control.
Validate Performs validation and updates the IsValid property.

Example 1: RequiredFieldValidator Control

<html>
<head>
    <script runat="server">
        protected void Submit_Click(Object sender,EventArgs e)
        {
            if (IsValid)
                Response.Redirect("NewPage.aspx");
        }
    </script>
</head>
<body>
    <form id="Form1" runat="server">
        User Name: <asp:textbox id="uname" runat="server">Enter User Name: 
        </asp:TextBox>
        <asp:RequiredFieldValidator id="unameVal" runat="server" 
        controltovalidate="uname" errormessage="Enter user name" 
        initialvalue="Enter User Name:" display="dynamic" text="Error: Enter User 
        Name!!!"/>
        Password: <asp:textbox id="pwd" textmode="password" runat="server"/>
        <br><br>
        <asp:button id="submit" text="Submit" OnClick="Submit_Click" 
        runat="server"/>
        <br><br>
        <asp:RequiredFieldValidator id="pwdVal" runat="server" 
        controltovalidate="pwd" errormessage="Enter password" display="static" 
        text="Error: Enter Password!!!" />
    </form>
</html>
RequiredFieldValidator

When the form is submitted, the page's IsValid property is checked, this property is true if there is no error occurs otherwise false and the user is shown with the error messages.

CompareValidator Control

This control is used to check the value of a control by comparing it with the value of another control in a form. You can set the data type of the values being compared and the operator to be used for comparison of values. For instance, you can check if the date of joining of an employee is greater than his date of birth or less than current date.

The properties of CompareValidator control is same as RequiredFieldValidator control in addition it has some more properties which are shown in below table.
Property Description
ControlToCompare Specifies the ID of the control to use for comparing values.
ValueToCompare Specifies the value used when performing comparison.
Operator Gets or sets the comparison operator to use. Possible values are: Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, and DataTypeCheck.
Type Gets or sets the data type to use when comparing values. Possible values are: String, Integer, Double, DateTime, and Currency.

Example 2: CompareValidator Control

<html>
<head>
    <script runat="server">
        protected void Submit_Click(Object sender,EventArgs e)
        {
            if (IsValid)
                Response.Redirect("NewPage.aspx");
        }
    </script>
</head>
<body>
    <form id="Form1" runat="server">
        Enter Old Password: <asp:textbox id="oldpwd" runat="server"/>
        <asp:CompareValidator id="oldpwdVal" runat="server"  controltovalidate="oldpwd" valuetocompare="mypassword" display="dynamic" type="String" operator="Equal" text="Error: Incorrect Password!!!" />
        <p>Enter new password: <asp:textbox id="newpwd" runat="server"/>
        <p>Confirm new password: <asp:textbox id="confpwd" runat="server"/>
        <p><asp:CompareValidator id="confpwdVal" runat="server" controltovalidate="confpwd" controltocompare="newpwd" type="String" operator="Equal" display="static" text="Error: Passwords do not match!!!" />
        <p><asp:button id="submit" text="Submit" onclick="Submit_Click" runat="server"/>
    </form>
</body>
</html>
CompareValidator

Checking Data Type: The following example shows how you can use the CompareValidator control to check the data type of the value entered in the asp controls. For example, you can check whether the user has entered a date in a date field, a string in a string field, and a number in a number field by using the DataTypeCheck property of the validator control.

Example 3: Data Type Check

<html>
<head>
    <title>CompareValidator DataTypeCheck</title>
    <script Runat="Server">
        protected void Button_Click( Object sender, EventArgs e)
        {
            if (IsValid)
                Response.Redirect("NewPage.aspx");
        }
    </script>
</head>
<body>
    <form id="Form1" Runat="Server">
		Enter your date of birth to know your future:
		<asp:TextBox id="txtBirthDate" Runat="Server"/>
		<asp:CompareValidator ID="CompareValidator1" ControlToValidate="txtBirthDate" Display="Dynamic" Text="Invalid birth date!" Operator="DataTypeCheck" Type="Date" Runat="Server" />
		<p><asp:Button ID="Button1" Text="Submit" OnClick="Button_Click" Runat="Server"/>
	</form>
</body>
</html>
DataTypeCheck

CompareValidator control requires date format as: 1/1/2002 or 1-1-2002.

RangeValidator Control

This control checks that the value in the control being validated falls within a specified range. The range can be specified using the attributes MinimumValue and MaximumValue. The values can be dates, numbers, or strings.

The properties and methods of the RangeValidator control are same as RequiredFieldValidator control. It has some additional properties which are shown in Table
Property Description
MaximumValue Specifies the maximum value in the range of permissible values.
MinimumValue Specifies the minimum value in the range of permissible values.

Example 4: Range Check using compare validator: The quantity of the ordered item must be between 10 and 50 kg

<html>
<head>
    <title>CompareValidator Range Check</title>
    <script Runat="Server">
        protected void Button_Click( Object sender, EventArgs e)
        {
            if (IsValid)
                Response.Redirect("NewPage.aspx");
        }
    </script>
</head>
    <body>
	    <form id="Form1" Runat="Server">
            Minimum Value: <asp:TextBox id="txtMinValue" text="10" Runat="Server"/>
			Maximum Value: <asp:TextBox id="txtMaxValue" text="100" Runat="Server"/>
			<p>Enter Value: <asp:TextBox id="txtRangeNumber" Runat="Server"/>
			<asp:CompareValidator ID="CompareValidator1" ControlToValidate="txtRangeNumber" ControlToCompare="txtMinValue" Display="Dynamic" Text="Number must be greater than minimum value!" Operator="GreaterThan" Type="Integer" Runat="Server" />
            <asp:CompareValidator ID="CompareValidator2" ControlToValidate="txtRangeNumber" ControlToCompare="txtMaxValue" Display="Dynamic" Text="Number must be less than maximum value!" Operator="LessThan" Type="Integer" Runat="Server" />
		    <p><asp:Button ID="Button1" Text="Submit" OnClick="Button_Click" Runat="Server"/>
        </form>
    </body>
</html>
RangeCheck

Example 5: RangeValidator Control

<html>
<head>
    <title>CompareValidator Range Check</title>
    <script Runat="Server">
    protected void Button_Click( Object sender, EventArgs e)
    {
        if (IsValid)
            Response.Redirect("NewPage.aspx");
    }
	protected void Page_Load(Object sender, EventArgs e)
	{
		if (!Page.IsPostBack)
		{
			mylist.Items.Add("Flour");
			mylist.Items.Add("Rice");
			mylist.Items.Add("Wheat");
			mylist.Items.Add("Sugar");
		}
	}
    </script>
</head>
    <body>
	    <form id="Form1" Runat="Server">
            Select item: <asp:dropdownlist id="mylist" runat="server"/>
			<p>Enter quantity: <asp:textbox id="qty" runat="server"/>
			<p><asp:RangeValidator id="qtyVal" runat="server" controltovalidate="qty" minimumValue="10" maximumValue="100" type="Integer" display="static" text="Error: Quantity ordered must be between 10 and 100 KGs!!!" />
            <p><asp:button id="submit" text="Submit" OnClick="Button_Click" runat="server"/>
        </form>
    </body>
</html>
RangeValidator

RegularExpressionValidator Control

You can use this control to check whether a user has entered a valid e-mail address, telephone number, user name or password in the asp.net control.

The properties and methods of this control are same as RequiredFieldValidator control. It has an additional property, ValidationExpression, this property is used to specify the regular expression to be used for performing validation.

Example 6: Password field should contains only letters or digits, No special characters are allowed.

<html>
<head>
    <title>CompareValidator Range Check</title>
    <script Runat="Server">
    protected void Button_Click( Object sender, EventArgs e)
    {
        if (IsValid)
            Response.Redirect("NewPage.aspx");
    }
    </script>
</head>
    <body>
	    <form id="Form1" Runat="Server">
            <p>Enter User Name: <asp:textbox id="uname" runat="server"/>
			<p>Enter Password: <asp:textbox id="pwd" runat="server"/>
			<asp:RegularExpressionValidator id="pwdVal" runat="server" controltovalidate="pwd" validationexpression="[A-Z a-z 1-9]*" display="static" text="Error: Password contain only letters or digits!!!" />
			<p><asp:button id="submit" text="Submit" onclick="Button_Click" runat="server"/>
        </form>
    </body>
</html>
RegularExpressionValidator
The following table summarizes the commonly used regular expressions
Symbol Meaning
[abc] Matches any character in the set
[^abc] Excludes any character in the set
{N} N matches
{N,} N or more matches
{N,M} Between N and M matches
$ End of input text X$
. Any single character except the newline (\n) i.ation
* Zero or more matches ra*t
+ One or more matches ra+t
? Zero or one matches ra?t
\s Matches whitespace characters like, space, tab, new line etc. \sa
\S Matches any non-whitespace character \SF
\b Matches a backspace ion\b
\B Any position that isn't a word boundary \BX\B
\d Matches any decimal character
\D Matches any non-decimal character
\t Matches a tab
\r Matches a carriage return
\n Matches a new line
\w Matches any alphanumeric character and underscore
\W Matches any non-word character

Examples of Regular Expressions
• Product code contains a single capital letter and 3 numerals: [A-Z][0-9]{3}
• To validate an email address: \S+@\S+\.\S{2,3}
• User names contain only alphanumeric characters or the underscore character, which consist of one or more word characters: \w+
• Password field contain between 8 and 30 characters: \w{8,30}
• You can validate a URL using the regular expression: http://\S+\.\S+
• A multi-line text box control does not have any MaxLength property. You can limit a user to 100 characters using the regular expression: .{0,100}
• Pin codes contain 6 digits: \d{6}
• In a similar manner you can check that telephone numbers.

ValidationSummary Controls

You can use the ValidationSummary control to present a summary of all the errors in a page at a single location.

ValidationSummary properties are:
Property Description
Display Sets the formatting for the error messages displayed by the control. Possible values are: BulletList (default), List, SingleParagraph.
EnableClientScript Enables or disables client-side form validation. By default, True.
Enabled Enables or disables both server and client-side form validation. By default, True.
HeaderText Sets the text that is displayed at the top of the summary of error messages.
ShowMessageBox When True, shows error messages in a pop-up message box.
ShowSummary Enables or disables the summary of error messages. By default, True.

Example 7: ValidationSummary Control

<html>
    <head>
    <title>Validation Summary Control</title>
<script Runat="Server">
    protected void Button_Click( Object sender, EventArgs e)
    {
        if (IsValid)
            Response.Redirect("NewPage.aspx");
    }
</script>
</head>
    <body>
	    <form id="Form1" Runat="Server">
            User Name:<asp:textbox id="uname" runat="server"/>
            <asp:RequiredFieldValidator id="unameVal" runat="server"  controltovalidate="uname" errormessage="Enter user name" display="none" />
            <p>Password:<asp:textbox id="pwd" textmode="password" runat="server"/>
            <asp:RequiredFieldValidator id="pwdVal1" runat="server" controltovalidate="pwd" errormessage="Enter password" display="none" />
            <asp:RegularExpressionValidator id="pwdVal2" runat="server" controltovalidate="pwd" validationexpression="[A-Z a-z 1-9]*" errormessage="Password must contain only letters or digits" display="none" />
            <p><asp:button id="submit" text="Submit" onclick="Button_Click"  runat="server"/>
            <p><asp:ValidationSummary id="valCtrl" runat="server" headertext="List of Errors" showsummary="true" displaymode="list"/>
        </form>
    </body>
</html>
validationsummary

You can use the ValidationSummary control's ShowMessageBox property to show error messages in a pop-up dialog box.

Using Validation Groups

If you added more than one form in a page, and both forms contained validation controls, the validation controls in both forms were evaluated regardless of which form you submitted.

For example, imagine that you wanted to create a page that contained both a login and registration form. If both forms included validation controls, submitting the login form caused any validation controls contained in the registration form to be evaluated.

Example 8: ShowValidationGroup Control

<html>
    <head>
    <title>Show Validation Groups</title>
<script Runat="Server">
    protected void btnLogin_Click(Object sender, EventArgs e)
    {
        if (Page.IsValid)
            lblLoginResult.Text = "Log in successful!";
    }
    void btnRegister_Click(Object sender, EventArgs e)
    {
        if (Page.IsValid)
            lblRegisterResult.Text = "Registration successful!";
    }
</script>
<style>
html{
	background-color:silver;
}
.column{
	float:left;
	width:300px;
	margin-left:10px;
	background-color:white;
	border:solid 1px black;
	padding:10px;
}
</style>
</head>
    <body>
	    <form id="Form1" Runat="Server">
            <div class="column">
                <fieldset>
                    <legend>Login</legend>
                    <p>Please log in to our Website.</p>
                    <asp:Label id="lblUserName" Text="User Name:" AssociatedControlID="txtUserName" Runat="server" />
                    <br>
                    <asp:TextBox id="txtUserName" Runat="server" />
                    <asp:RequiredFieldValidator id="reqUserName" ControlToValidate="txtUserName" Text="(Required)" ValidationGroup="LoginGroup" Runat="server" />
                    <br><br>
                    <asp:Label id="lblPassword" Text="Password:" AssociatedControlID="txtPassword" Runat="server" />
                    <br>
                    <asp:TextBox id="txtPassword" TextMode="Password" Runat="server" />
                    <asp:RequiredFieldValidator id="reqPassword" ControlToValidate="txtPassword" Text="(Required)" ValidationGroup="LoginGroup" Runat="server" />
                    <br><br>
                    <asp:Button id="btnLogin" Text="Login" ValidationGroup="LoginGroup" Runat="server" OnClick="btnLogin_Click" />
                </fieldset>
                <asp:Label id="lblLoginResult" Runat="server" />
            </div>
        <div class="column">
        <fieldset>
            <legend>Register</legend>
            <p>If you do not have a User Name, please register at our Website.</p>
            <asp:Label id="lblFirstName" Text="First Name:" AssociatedControlID="txtFirstName" Runat="server" />
            <br>
            <asp:TextBox id="txtFirstName" Runat="server" />
            <asp:RequiredFieldValidator id="reqFirstName" ControlToValidate="txtFirstName" Text="(Required)" ValidationGroup="RegisterGroup" Runat="server" />
            <br><br>
            <asp:Label id="lblLastName" Text="Last Name:" AssociatedControlID="txtLastName" Runat="server" />
            <br>
            <asp:TextBox id="txtLastName" Runat="server" />
            <asp:RequiredFieldValidator id="reqLastName" ControlToValidate="txtLastName" Text="(Required)" ValidationGroup="RegisterGroup" Runat="server" />
            <br><br>
            <asp:Button id="btnRegister" Text="Register" ValidationGroup="RegisterGroup" Runat="server" OnClick="btnRegister_Click" />
        </fieldset>
        <asp:Label id="lblRegisterResult" Runat="server" />
    </div>
        </form>
    </body>
</html>
validationgroup

CustomValidator Control:

If none of the validation controls support the validation requirements of an ASP.NET application, a custom validator control can be created. For Example, You can use validation control to check the user name and password of the user from a database, check if the user has enough funds in his/her bank account to purchase an item from your site. This validation will be performed entirely on the server-side.

The properties and methods of the CustomValidator control are same as RequiredFieldValidator control. It has some additional properties, methods and events which are shown below:

Property Description
ClientValidationFunction Specifies the name of the client-side validation function.
Method Description
OnServerValidate Raises the ServerValidate event.
Event Description
ServerValidate Represents the server-side validation function.

The ServerValidateEventArgs parameter has the following 2 properties:
• IsValid: When True, the validation check is successful.
• Value: Value of the control being validated.

The client-side validation subroutine is similar except that it is written in a scripting language. You can catch the validation subroutines to the CustomValidator control through the properties, ClientValidationFunction, and OnServerValidate.

Example 9: CustomValidator Control: checks if the string entered in a textbox is the 8 characters long or not.

<html>
    <head>
    <title>Show Validation Groups</title>
<script Runat="Server">
    protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
    {
        if(e.Value.Length == 8)
            e.IsValid = true;
        else
            e.IsValid = false;
    }
</script>
</head>
    <body>
	    <form id="Form1" Runat="Server">
            Custom text:<br>
            <asp:TextBox runat="server" id="txtCustom" />
            <asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtCustom" onservervalidate="cusCustom_ServerValidate" errormessage="The text must be exactly 8 characters long!" /> <br>
            <asp:button id="submit" text="Submit" runat="server"/>
        </form>
    </body>
</html>
customValidator

Disabling Validation:

Every form contains a Submit button to submit the details and a Cancel button that can be used to reset the data entered by the user in the form. This is required if the user has changed his mind about filling the form and wishes to go to another page. Canceling the form when the form contains validation controls is not easy. You can get around this problem by using the CausesValidation property of the Button control. This property can be used to enable or disable validation when the button is clicked.

Example 10: Disabling Validation

<html>
    <head>
    <title>Show Validation Groups</title>
<script Runat="Server">
    protected void Submit_Click(Object sender, EventArgs e)
    {
        if (IsValid)
            Response.Redirect("NewPage.aspx");
    }
    protected void Cancel_Click(Object s, EventArgs e)
    {
        Response.Redirect("Cancel.aspx");
    }
</script>
</head>
    <body>
	    <form id="Form1" Runat="Server">
            User Name: <asp:textbox id="uname" runat="server">Enter User Name: </asp:TextBox>
            <asp:RequiredFieldValidator id="unameVal" runat="server" controltovalidate="uname" errormessage="Enter user name" initialvalue="Enter User Name:" display="dynamic" text="Error: Enter User Name!!!"/>
            Password: <asp:textbox id="pwd" textmode="password" runat="server"/> <br> <br>
            <asp:button id="submit" text="Submit" onclick="Submit_Click" runat="server"/> <br><br>
            <asp:RequiredFieldValidator id="pwdVal" runat="server" controltovalidate="pwd" errormessage="Enter password" display="static" text="Error: Enter Password!!!" /> <br>
            <asp:button id="cancel" text="cancel" onclick="Cancel_Click" CausesValidation="False" runat="server"/>
        </form>
    </body>
</html>
DisablingValidation

You can disable client-side form validation by using the following page directive:

<%@ Page ClientTarget="DownLevel" %>
    Or
Set the EnableClientScript property to False.

This directive forces validation to be performed only on the server-side.