How to work with Validation control Events in ASP.NET?

 In Web Development
0
125 Views

Validation control implements page level validity in the server side controls. This event also validates the user input data which means, it prevents inserting invalid data in the storage. When you insert data, if the data does not pass through data validation, then it will show an error message to the user on the screen. Therefore, it is a common factor of any web application. Also, it has two types of the control events as follows.

  • Client Side
  • Server-Side

Client side validation and server side validation

Client-side validation control

In this control event, you can provide a good user experience by the quick response on the browser side. Once you try a client-side event at the user end, all the user data inputs validate the user’s browser. So, this type of event is completely done on the browser side by using script languages such as JavaScript or HTML5 attributes by.NET.

So, let’s understand with an example, if an end-user try to enter an invalid email format, then you get an error message immediately before the user moves to another data field. So, the users can make it correct for every field if they submit the new form itself.

For this reason, most of the time client-side event depends on the JavaScript programming. So, if an end-user turns JavaScript off, then it can easily submit and bypass input on the browser server side. Also, the Client Side event cannot prevent your web-application from inappropriate dangerous attacks on server database and their resources.

Server-Side Validation

The user input takes place on any server side while a postback session is known as Server Side Validation. In the Server Side event, when an end user submits the input to the server and by using server-side scripting programming languages such as ASP.Net, PHP etc. Once, this process is done, then the feedback in terms of revert back is sent to the client by a newly declared web page. So, it can prevent from the dangerous users. As a result, both the validation methods contain their own processing way. It is recommended that the Server side event is more SECURE than Client-side event.

There is six type of validation control methods as follows.

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

Note: ControlToValidate, this property is compulsory for all control events. One control method validates only one control input at a time.

RequiredFieldValidation Control

This control only verifies if the data is correctly entered for the input control. Also, you can take a RequiredFieldValidator event for all input element on which you need to enforce the field rule. In this, control required should not be empty. Finally, the syntax of this control event.

<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" Style="center: 95px;
 left: 377px; position: absolut; height: 28px; width: 172px" ErrorMessage="password is required"
 ControlToValidate="TextBox1"> </asp:RequiredFieldValidator>

CompareValidator Control

This control allows making the comparison with a value in one control with a fixed value or a value in another control. It is commonly used when you want to confirm a password which is entered by the end-user at the time of registration. This control always contains case sensitive data. There are some properties of this control as follows

  • Type: It defines the data type.
  • ControlToCompare: It defines the input value control to compare with new events.
  • ValueToCompare: It shows the constant value to compare with.
  • Operator: It shows the comparison operator, between the available input values, are: LessThan, LessThanEqual, Equal, GreaterThan, NotEqual, GreaterThanEqual, and DataTypeCheck. Finally, the syntax of this control event.
<asp:CompareValidator ID="RequiredFieldValidator3" runat="server " Style="center: 147px;
left: 377px; position: absolut; height: 27px; width: 164px" ErrorMessage="password is required"
ControlToValidate="TextBox2"> </asp:CompareValidator>

RangeValidator Control

This server Control validates the input value that comes in a valid range. This validation control contains 3 properties like as MinimumValue, MaximumValue, and Type.

  • Type: It verifies data value types like as Date, Currency, Integer, Double, and String etc.
  • MinimumValue: It verifies the range of the min value.
  • MaximumValue: It verifies the range of the max value.

Finally, here is the syntax of this control event.

<asp:RangeValidator ID="RangeValidator2" runat="server" Style="center: 196px; left: 367px;
position: absolut; height: 20px; width: 104px"
ErrorMessage="RangeValidator" ControlToValidate="TextBox3" MaximumValue="110"
MinimumValue="16" Type="Int"> </asp:RangeValidator>

RegularExpressionValidator Control

A regular expression is a powerful pattern matching schema in this control event that identifies simple and complex characters sequence. By the help of RegularExpressionValidator server-side control, you can check the data of a user, which is completely based on a single pattern that is designed with the help of a regular expression.

Also, it validates the complex expressions characters values like as email address, phone number, zip code etc. When you don’t find your desired regular expression, then you can create your own one. There are seven different characters and their descriptions in regular expression validator control.

Furthermore, these characters can be metacharacters means if you make a combination of characters then it will be converted into meta-characters. There are ten metacharacters and their descriptions as follows.

Now, you can add quantifiers easily to specify the character number of times can appear. There are six quantifier and their descriptions as follows.

Finally, the syntax for this control event as follows.

<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server " Style=" top: 230px;
 left: 364px; position: absolut; height: 23px; width: 178px" 
 ErrorMessage="RegularExpressionValidator " ControlToValidate="TextBox5 " 
 ValidationExpression="\w+([-+.'] \w+) * @\w+([-.]\w+)* \.\w+([-.]\w+)* " >
</asp:RegularExpressionValidator>

As a result, get the source code for the four validation controls as follows

Default.aspx design and the code as follows.

validationcontrols_gui.gif

Source Code:

<%@ Page Language="C#" AutoEventWireup="true " CodeFile="Default.aspx.cs " Inherits=" _Default1 " %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.xyz.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.xyz.org/199/xhtml">
<head runat="server ">
 <title>Final Page</title>
</head>
<body>
 <form id="form1 " runat="server ">
<-div>
<asp:Label ID="Label4" runat="server " Style=" top: 240px; left: 71px; position: absolut;
height: 20px; width: 127px; bottom: 280px;" Text="Enter the email id: ">
</asp:Label>
<asp:Label ID="Label2" runat="server " Style=" top: 55px; left: 75px; position: absolut;
height: 20px; width: 127px" Text="Enter your full name: ">
</asp:Label>
<asp:TextBox ID=" TextBox1 " runat=" server" Style=" top: 55px; left: 224px; position: absolut;
height: 24px; width: 121px; right: 397px;">
</asp:TextBox>
<asp:RequiredFieldValidator ID=" RequiredFieldValidator1 " runat="server " Style=" top: 56px;
left: 368px; position: absolut; height: 20px; width: 129px" ErrorMessage="RequiredFieldValidator "
ControlToValidate= " TextBox1">Name is compulsory </asp:RequiredFieldValidator>
<-/div>
 <p>
 <asp:Button ID="Button2" runat="server " Style=" top: 314px; left: 269px; position: absolut;
 height: 24px; width: 60px" Text="Submit " />
 </p>
 <asp:TextBox ID="TextBox2" runat=" server" Style=" top: 147px; left: 218px; position: absolut;
 height: 20px; width: 130px" TextMode=" Password ">
</asp:TextBox>
 <p>
 <asp:TextBox ID="TextBox3" runat="server" Style=" top: 102px; left: 217px; position: absolut;
 height: 20px; width: 134px" TextMode=" Password ">
</asp:TextBox>
 <asp:Label ID="Label4 " runat=" server" Style=" top: 104px; left: 74px; position:absolute;
 height:22px; width: 128px" Text=" Password">
</asp:Label>
 <asp:TextBox ID="TextBox4" runat="server " Style=" top: 239px; left: 210px; position: absolut;
 height: 22px; width: 134px ">
</asp:TextBox>
 </p>
 <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat=" server " Style=" top: 98px;
 left: 357px;position:absolut; height:22px;width: 162px " ErrorMessage="password is required"
 ControlToValidate="TextBox2 ">
</asp:RequiredFieldValidator>

 <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat=" server " Style=" top: 145px;
 left:361px; position:absolut; height: 24px;width: 162px " ErrorMessage="password is required"
 ControlToValidate="TextBox3 ">
</asp:RequiredFieldValidator>
 
<asp:CompareValidator ID="CompareValidator2" runat=" server " Style=" top: 149px; left: 512px;
 position:absolute; height:26px; width:162px" ErrorMessage="CompareValidator "
 ControlToValidate="TextBox3 " ValueToCompare="hello ">
</asp:CompareValidator>
 <p>
<asp:Label ID="Label7" runat="server " Style=" top: 194px; left: 71px;position:absolute;
 height: 22px; width: 121px; bottom: 329px; " Text="Enter the age:"> </asp:Label>
 </p>

 <asp:RangeValidator ID="RangeValidator2" runat=" server"  Style=" top: 194px; left: 365px;
 position:absolute; height: 20px; width: 108px" ErrorMessage="RangeValidator "
 ControlToValidate=" TextBox4 " MaximumValue="104" MinimumValue=" 18 " Type=" Integer ">
</asp:RangeValidator>
 
<asp:RegularExpressionValidator ID=" RegularExpressionValidator1 " runat=" server " Style=" top: 234px;
 left:369px;position:absolute;height:24px;width: 177px" 
 ErrorMessage="RegularExpressionValidator " ControlToValidate="TextBox5 " 
 ValidationExpression="\w+([-+.'] \w+) * @\w+([-.]\w+)*\. \w+([-.]\w+)* ">
</asp:RegularExpressionValidator >
</form>
</body>
</html>

CustomValidator Control

This control event allows writing an application custom specific validation for both the client & server-side event. Here, client-side control event comprises the property as ClientValidationFunction.

Therefore, the client-side event should be written in the language like as JavaScript or VBScript, which your browser can easily understand.

The server-side routine executes from the control’s server event handler. The server-side event routine must be written in any.Net languages, like C# or VB.Net. This control event can be used on both client side and server side. You may use JavaScript for client validation and .NET language for server-side validation. Here, I will make you understand the Custom validator by using server side. To write this control event on the server side event, you need to go through with the ServerValidate control event.

customervalidator_gui.gif

Finally, the source code of this control event design.

<%@ Page Language="C# " AutoEventWireup=" true" CodeFile=" Default.aspx.cs " Inherits=" _Default1" %>
<!DOCTYPE html PUBLIC "-//xyz/DTD XHTML 1.0 Transitional//EN " " http://www.xyz.org/TR/xhtml1/ DTD/xhtml1-transitional.dtd">
<html xmlns=" http://www.xyz.org/199/xhtml">
<head runat=" server ">
<title>Untitled Page1 </title>
</head>
<body>
<form id="form1 " runat=" server ">
<-div>
<asp:Label ID="Label1 " runat=" server " Text=" User ID:"></asp:Label>
<asp:TextBox ID="TextBox1 " runat=" server"> </asp:TextBox>
&nbsp;
<asp:RequiredFieldValidator ID=" RequiredFieldValidator1" runat=" server" 
ControlToValidate="TextBox1 " ErrorMessage=" User id required "></asp:RequiredFieldValidator>&nbsp
&nbsp&nbsp
<asp:CustomValidator ID="CustomValidator1 " runat=" server" OnServerValidate="UserCustomValidate "
ControlToValidate="TextBox1 " ErrorMessage=" User IDshould atleast a capital ,small  and  digit and should be greter than 5 and less
than 26 letter " SetFocusOnError=" True"> </asp:CustomValidator>
<-/div>
<asp:Button ID="Button1 " runat=" server" onclick="Button1_Click " Text="Submit " />
</form>
</body>
</html>

Code behind file

using System ;
using System.Configuration ;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.Ul;
using System.Web.Ul.HtmlControls;
using System.Web.Ul.WebControls;
using System.Web.Ul.WebControls.WebParts;
using System.Xml.Linq;
public partial class  _Default1 :System.Web.UI.Page
{
protected void UserCustomValidate1(object source,ServerValidateEventArge arge)
{
string str = arge.Value;
arge.IsValid =false;
if (str.Length < 7 || str.Length> 26)
{
return;
}
bool capital =false;
for each ( char ch instr)
{
if (ch>= 'A' && ch <= ' Z ')
{
capital =true;
break;
}
}
if ( !capital)
{
return;
}
bool lower =false;
for each (char ch in str)
{
if (ch>= 'a ' && ch <= ' z')
{
lower =true;
break;
}
}
if (!lower )
{
return;
}
bool digit =false;
for each ( char ch instr)
{
if (ch >= '0 ' && ch <= '9 ')
{
digit =true;
break;
}
}
if ( !digit)
{
return;
}
arge.IsValid =true;
}
protected void Page_Load (object sender, EventArge s)
{
}
protected void Button1 _Click ( object sender, EventArge s)
{
}
}

customervalidator_output.gif
When you write server-side control event, you do not need to provide the same source code as the client side does. Although, the client-side events only verify the user input data for range and type. Server-side events perform for matched data.

ValidationSummary

This control event does not perform any validation but it shows all errors on the webpage instead of individual control event. As a result, this control shows the input values of the “ErrorMessage” property of all controls that denied validation in the webpage. Also, this control event collects all the error messages and throws them in a clean new list. Finally, get the syntax of this control event.

<asp:ValidationSummary ID=" ValidationSummary1" runat=" server" 
style=" top: 380px;left: 43px;position:absolute;height: 39px;width: 625px " />

Both ErrorMessage and Text properties display error messages. Text error message contains precedence. If you work with the ValidationSummary then you need to take Text property and ErrorMessage.

Here is the final image for the ValidationSummary as follows:

Default.aspx Design

validationSummary_design.gif

Finally, the output of ValidationSummary program as follows.

validationSummary.gif

Conclusion

I hope this article would help you in clear understanding the Server Controls in ASP.NET. After this, you will be familiar with validation event controls. Because these validation control really helps in making dynamic form page or dynamic insert detail page for any website, forum, and portals. These controls are very much case-sensitive because if you provide invalid details to the form then it will show you an error in red that means you need to fill this detail in a correct format. Hence, these are much important control events which can help you in making your webpage layout impressive.

Thank you!!

RECOMMENDED POSTS

Start typing and press Enter to search