Performing Form Validation using Validation (ASP.NET Tutorial)

in #utopian-io7 years ago (edited)

Lesson Objectives

A. Performing Form Validation using Validation
B. Client-side and Server-side validation
C. Demonstration: Performing Validation using Validation Controls

Needs are;

A.Asp.NET
B. Visual Studio
C. C#

The difficulty level of commands we use is middle.

Validation of User Input

Validation is the process of checking the values entered by users for correctness. For example, the age entered by a user should be a numeric.The Email ID entered by a user should be in a proper format. Validation is done to avoid errors during processing the input from the user and to ensure that valid data is entered by the user.

Client-side and Server-side validation

Validation can be done on the browser or on the server. Accordingly it is classified as Clientside validation and Server-side validation. JavaScript can be used to do client-side validation. C#.NET is used as the scripting language for server-side validation. Client-side validation has an advantage as the validation is done instantly on the client itself and the server need not do the validation. This helps the server to process data faster as the server need not do the validation. On the other hand server-side validation provides more security as the validation is done on the server and is hidden from the client.

Validation Controls:

ASP.NET provides several validation controls which act as a mechanism for checking the user input for its correctness. The validation check may be for a specific format or a valid range of data. The various validation controls are RequiredFieldValidator, RangeValidator,RegularExpressionValidator, CompareValidator, CustomValidator ,ValidationSummary and DynamicValidator.

The Toolbox with Validation Controls is given below:

The RequiredFieldValidator control is used to check if the user has entered data in the control and did not leave it empty. Below is the code for the RequiredFieldValidator which checks if the user has entered a value in the txtNameTextBox.

<asp:RequiredFieldValidator ID="rfvName"
runat="server"ControlToValidate="txtName"
ErrorMessage="Customer Name cannot be blank.”
</asp:RequiredFieldValidator>

The RangeValidatorcontrol is used to check if the user has entered a value within a valid range. Below is the code for the RangeValidator which checks if the user has entered a value between 20 and 60 in the txtAgeTextBox.

<asp:RangeValidator ID="rvAge" runat="server" ControlToValidate="txtAge"
Type="Integer"MinimumValue="20" MaximumValue="60"
ErrorMessage="Age should be between 20 to 60.">
</asp:RangeValidator>

The RegularExpressionValidatorcontrol is used to check if the user has entered a value which matches a regular expression. Below is the code for the RegularExpressionValidator which checks if the user has entered a valid Email ID in the txtEmailTextBox.

<asp:RegularExpressionValidator ID="revEmail" runat="server"
ControlToValidate="txtEmail" ErrorMessage="Email ID is invalid."
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>

The CustomValidator control is used to validate the data entered by the user using a userdefined function. Below is the code for the CustomValidator which checks if the user has entered a password which is at least 6 characters or greater.

<asp:CustomValidator ID="cvPassword" runat="server"
ControlToValidate="txtPassword"
ClientValidationFunction="chkPassword"
ErrorMessage="Password length should be 6 or greater.">
</asp:CustomValidator>

The CompareValidatorcontrol is used to check if the user has entered a value which matches the value in another control. Below is the code for the CompareValidator which checks if the user has entered the same password in the txtPassword and txtConfirmPasswordTextBoxes.

<asp:CompareValidator ID="cvConfirmPassword" runat="server"
ControlToValidate="txtConfirmPassword" ControlToCompare="txtPassword"
ErrorMessage="Password and Confirm Password does not match.">
</asp:CompareValidator>

The ValidationSummarycontrol is used to display a summary of all the validation errors in the web page. Below is the code for the ValidationSummary which displays all the errors in the web page.

<asp:ValidationSummary ID="vsCustomerDetails" runat="server" />

Demonstration: Performing Validation using Validation Controls.

Steps to create the Web Page
1 ) Create a new web form named ValidationControlsDemo.aspx

2 ) Design the form as below by reusing the table and controls created in the
WebServerControlsDemo. Add a TextBox to accept Age. Add the required Validation Controls.

3 ) The various controls and their properties to be used to design the form are given in the table below:


4 ) Write the code for ValidationControlsDemo.aspx file

<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="ValidationControlsDemo.aspx.cs"
Inherits="ValidationControls_RequiredFieldValidatorDemo" %>
<!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>Validation Server Controls Demo</title>
<style type="text/css">
#form1
{
height: 612px;
width: 991px;
}
</style>
<script type="text/javascript">
function chkPassword(oSrc, args) {
args.IsValid = (args.Value.length > 6);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Table ID="Table1" runat="server" Style="z-index: 1; left: 183px; top: 16px;
position: absolute; width: 889px">
<asp:TableRow ID="TableRow1" runat="server" Height="50px">
<asp:TableCell ID="TableCell1" runat="server" ColumnSpan="2"
HorizontalAlign="Center">
<b style="font-size: x-large; font-weight: bold;">Customer Registration
Form</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow2" runat="server" HorizontalAlign="Left" Style="fontsize:
large">
<asp:TableCell ID="TableCell3" runat="server">Customer Name</asp:TableCell>
<asp:TableCell ID="TableCell4" runat="server">
<asp:TextBox ID="txtName" runat="server" Width="211px"></asp:TextBox>
</asp:TableCell>
<asp:TableCell ID="TableCell24" runat="server">
<asp:RequiredFieldValidator ID="rfvName" runat="server"
ControlToValidate="txtName"
ErrorMessage="Customer Name cannot be
blank."></asp:RequiredFieldValidator>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow3" runat="server" HorizontalAlign="Left" Style="fontsize:
large">
<asp:TableCell ID="TableCell5" runat="server">Customer Address</asp:TableCell>
<asp:TableCell ID="TableCell6" runat="server">
<asp:TextBox ID="txtAddress" runat="server" TextMode="MultiLine"
Width="211px">
</asp:TextBox>
</asp:TableCell>
<asp:TableCell ID="TableCell25" runat="server">
<asp:RequiredFieldValidator ID="rfvAddress" runat="server"
ControlToValidate="txtAddress"
ErrorMessage="Customer Address cannot be
blank."></asp:RequiredFieldValidator>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow4" runat="server" HorizontalAlign="Left" Style="fontsize:
large">
<asp:TableCell ID="TableCell7" runat="server">Gender</asp:TableCell>
<asp:TableCell ID="TableCell8" runat="server">
<asp:RadioButton ID="rbMale" runat="server" Font-Bold="True" Font-
Size="Medium" Text="Male"
GroupName="Gender" />
<asp:RadioButton ID="rbFemale" runat="server" Font-Bold="True" Font-
Size="Medium"
Text="Female" GroupName="Gender" />
</asp:TableCell>
<asp:TableCell ID="TableCell26" runat="server">
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow12" runat="server" HorizontalAlign="Left"
Style="font-size: large">
<asp:TableCell ID="TableCell18" runat="server">Age</asp:TableCell>
<asp:TableCell ID="TableCell23" runat="server">
<asp:TextBox ID="txtAge" runat="server" Width="211px"></asp:TextBox>
</asp:TableCell>
<asp:TableCell ID="TableCell29" runat="server">
<asp:RangeValidator ID="rvAge" runat="server" ControlToValidate="txtAge"
Type="Integer"
MinimumValue="20" MaximumValue="60" ErrorMessage="Age should
be between 20 to 60."></asp:RangeValidator>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow5" runat="server" HorizontalAlign="Left" Style="fontsize:
large">
<asp:TableCell ID="TableCell9" runat="server">Email ID</asp:TableCell>
<asp:TableCell ID="TableCell10" runat="server">
<asp:TextBox ID="txtEmail" runat="server" Width="211px"></asp:TextBox>
</asp:TableCell>
<asp:TableCell ID="TableCell27" runat="server">
<asp:RegularExpressionValidator ID="revEmail" runat="server"
ControlToValidate="txtEmail"
ErrorMessage="Email ID is invalid." ValidationExpression="\w+([-
+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow6" runat="server" HorizontalAlign="Left" Style="fontsize:
large">
<asp:TableCell ID="TableCell11" runat="server">Password</asp:TableCell>
<asp:TableCell ID="TableCell12" runat="server">
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"
Width="211px"></asp:TextBox>
</asp:TableCell>
<asp:TableCell ID="TableCell28" runat="server">
<asp:CustomValidator ID="cvPassword" runat="server"
ControlToValidate="txtPassword"
ClientValidationFunction="chkPassword" ErrorMessage="Password
length should be 6 or greater."></asp:CustomValidator>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow14" runat="server" HorizontalAlign="Left"
Style="font-size: large">
<asp:TableCell ID="TableCell36" runat="server">Confirm Password</asp:TableCell>
<asp:TableCell ID="TableCell37" runat="server">
<asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password"
Width="211px"></asp:TextBox>
</asp:TableCell>
<asp:TableCell ID="TableCell38" runat="server">
<asp:CompareValidator ID="cvConfirmPassword" runat="server"
ControlToValidate="txtConfirmPassword"
ControlToCompare="txtPassword" ErrorMessage="Password and Confirm
Password does not match."></asp:CompareValidator>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow7" runat="server" HorizontalAlign="Left" Style="fontsize:
large">
<asp:TableCell ID="TableCell13" runat="server">Subscription</asp:TableCell>
<asp:TableCell ID="TableCell14" runat="server">
<asp:DropDownList ID="ddlSubscription" runat="server" Width="211px">
<asp:ListItem>--Select--</asp:ListItem>
<asp:ListItem>Quarterly</asp:ListItem>
<asp:ListItem>Half Yearly</asp:ListItem>
<asp:ListItem>Anually</asp:ListItem>
</asp:DropDownList>
</asp:TableCell>
<asp:TableCell ID="TableCell30" runat="server">
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow10" runat="server">
<asp:TableCell ID="TableCell2" runat="server"></asp:TableCell>
<asp:TableCell ID="TableCell19" runat="server">
<asp:CheckBox ID="chkBooks" runat="server" Text="Books" Font-Size="Large"
Width="211px" />
</asp:TableCell>
<asp:TableCell ID="TableCell31" runat="server">
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow11" runat="server" HorizontalAlign="Left"
Style="font-size: large">
<asp:TableCell ID="TableCell20" runat="server">Area Of Interest</asp:TableCell>
<asp:TableCell ID="TableCell21" runat="server">
<asp:CheckBox ID="chkComputers" runat="server" Width="211px" Font-
Size="Large" Text="Computers" />
</asp:TableCell>
<asp:TableCell ID="TableCell32" runat="server">
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow8" runat="server">
<asp:TableCell ID="TableCell15" runat="server">
</asp:TableCell>
<asp:TableCell ID="TableCell16" runat="server">
<asp:CheckBox ID="chkMovies" runat="server" Width="211px" Font-Size="Large"
Text="Movies" />
</asp:TableCell>
<asp:TableCell ID="TableCell33" runat="server">
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow15" runat="server" Height="20px"
HorizontalAlign="Left"
Style="font-size: large">
</asp:TableRow>
<asp:TableRow ID="TableRow9" runat="server" HorizontalAlign="Left"
Style="font-size: large">
<asp:TableCell ID="TableCell17" ColumnSpan="2" HorizontalAlign="Center"
runat="server">
<asp:Button ID="btnSubmit" runat="server" Text="Submit" Font-Bold="True"
OnClick="btnSubmit_Click" />&nbsp;&nbsp;&nbsp;
<asp:Button ID="btnReset" runat="server" Text="Reset" Font-Bold="True"
OnClick="btnReset_Click" />
</asp:TableCell>
<asp:TableCell ID="TableCell34" runat="server">
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow13" runat="server" HorizontalAlign="Left"
Style="font-size: large">
<asp:TableCell ID="TableCell22" ColumnSpan="2" HorizontalAlign="Left"
runat="server">
<asp:ValidationSummary ID="vsCustomerDetails" runat="server" />
<asp:Literal ID="lInfo" runat="server"></asp:Literal>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</form>
</body>
</html>
5) Write the code for ValidationControlsDemo.aspx.cs file. The “btn_Submit_Click” is
a server-side event handler which is invoked when the user clicks the Submit button after
he fills the form. The “btn_Reset_Click” is a server-side event handler which is invoked
when the user clicks the Reset button to clear the values in the form.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class ValidationControls_RequiredFieldValidatorDemo :
System.Web.UI.Page
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
lInfo.Text = "<b>You have entered the following information </b><br><br>";
lInfo.Text = lInfo.Text + "Customer Name :<b>" + txtName.Text +
"</b><br>";
lInfo.Text = lInfo.Text + "Customer Address :<b>" + txtAddress.Text +
"</b><br>";
if (rbMale.Checked == true)
lInfo.Text = lInfo.Text + "Gender :<b> Male</b><br>";
if (rbFemale.Checked == true)
lInfo.Text = lInfo.Text + "Gender : <b>Female</b><br>";
lInfo.Text = lInfo.Text + "Age :<b>" + txtAge.Text + "</b><br>";
lInfo.Text = lInfo.Text + "Email ID :<b>" + txtEmail.Text + "</b><br>";
lInfo.Text = lInfo.Text + "Password :<b>" + txtPassword.Text + "</b><br>";
lInfo.Text = lInfo.Text + "Confirm Password :<b>" + txtConfirmPassword.Text +
"</b><br>";
lInfo.Text = lInfo.Text + "Subscription :<b>" + ddlSubscription.SelectedValue +
"</b><br>";
lInfo.Text = lInfo.Text + "Areas of Interest : ";
if (chkBooks.Checked == true)
lInfo.Text = lInfo.Text + "<b>&nbsp;Books</b>";
if (chkComputers.Checked == true)
lInfo.Text = lInfo.Text + "<b>&nbsp;Computers</b>";
if (chkMovies.Checked == true)
lInfo.Text = lInfo.Text + "<b>&nbsp;Movies</b><br>";
}
protected void btnReset_Click(object sender, EventArgs e)
{
txtName.Text = "";
txtAddress.Text = "";
rbMale.Checked = false;
rbFemale.Checked = false;
txtAge.Text = "";
txtEmail.Text = "";
txtConfirmPassword.Text = "";
ddlSubscription.SelectedIndex = 0;
chkBooks.Checked = false;
chkComputers.Checked = false;
chkMovies.Checked = false;
lInfo.Text = "";
}
}

6 ) Run the form. Click the submit button without entering any values. You will find the output below:

The above output displays the error messages produced by the RequiredFieldValidator controls and the summary of errors in the ValidationSummary control.

7 ) Stop the Application and run the web page again. Enter valid values for Customer Name and Customer Address. Enter invalid values for Age, Email ID, Password and Confirm Password fields and submit the form. You will find the output below :



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Hey @coderlovely I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Coin Marketplace

STEEM 0.18
TRX 0.15
JST 0.029
BTC 62716.82
ETH 2447.73
USDT 1.00
SBD 2.65