Performing Validations with ASP.NET - Part 1

原创 2004年10月06日 14:13:00
Imagine a user visits your site. Imagine also that your site sells books. The user first screens the available books on the site. While screening, they fill out a form, which would enable them to provide quantity details, address and other relevant information. Suppose, however, that your user submits the form without filling in the zip code. After submitting the form, the server returns an error indicating null field provided there is no proper error handling techniques employed on the server side script. It is here that the usage of validations should come into picture.

Validation means checking for accuracy and correctness of the entered data. By employing proper validations, you not only check for the above-mentioned criteria but also can prompt a user to enter a correct value and thereby avoid costly errors. These errors can be either due to carelessness of users or due to some other reason.

If you are not employing validations, then if the server returns an error, it may be unrecognizable for a user. This could tempt the user to leave your site. You could be losing an order and a valuable customer. These difficulties can be avoided if the form had been properly validated. During development, proper rules must be set to let the user know what to do if a specified error occurs. The form should have to be validated in such a way that the user should compulsorily enter data without which, the data cannot be submitted to the database on the server. You can also employ a system whereby your user could enter data in a required format such as only 5 digits for a zip code or a phone number in (---) --- --- format.

There are two types of validations like client-side and server-side. While client side validations can be performed using JavaScript and VBScript, server side validations can be achieved via classic ASP. The biggest problem with these languages and technologies is that you have to write lengthy code to perform a simple task. Since, VBScript won't work with Netscape browser, you cannot perform client-side validations using this language. You have to learn JavaScript or Classic ASP to perform validations.

With ASP.NET, these difficulties are eliminated. ASP.NET provides its own built-in controls for validations. You can easily place controls and write codes by using a text editor like Notepad or an IDE like Visual Studio .NET. Moreover, ASP.NET supports C#, Visual Basic .NET, and any other language in the Microsoft .NET family. ASP.NET provides six types of validation controls. They are
  • CompareValidator
  • CustomValidator
  • RangeValidator
  • RegularExpressionValidator
  • RequiredFieldValidator
  • ValidationSummary

Each of these above controls can be linked to .NET Web Form controls like TextBox, Dropdownbox, ListBoxes etc. Even though there are wide ranges of controls for validation, it is up to you to decide upon which control to use. It also depends up on your project needs. In this first part of this series, you will learn the application of first three controls with code listings using VB .NET and C#.

CompareValidator

As the name suggests, this control is used to compare the values of one control with another control. The comparison is done with the help of textboxes. The CompareValidator control has two important properties namely, Operator and Type. The Operator property is mainly used as a basis of comparison between two values (GreaterThan, LessThan, Equal, NotEqual etc) and Type property indicates the data type of the values like Integer, string etc.

To illustrate, copy or enter the code in Listing 1 and save the file with extension .aspx under the Inetpub/wwwroot directory. Be sure to install .NET Framework SDK or Visual Studio .NET before attempting this work.

I recommend that you use ASP.NET WebMatrix for coding and testing the listings shown on this article (See figure 1). If you are using this tool, then you need not worry about giving extensions, setting the language etc. The tool does the entire work for you. It also includes a built-in server, which can be activated upon pressing the F5 key. You can also set various properties from the IDE itself and the coding is automatically done in the background. Moreover, the tool does not eat up your valuable disk space and is easy to download (www.asp.net) and install. After all, it's free from Microsoft

validation_p1_1.jpg

Click here for larger image

<%@ Page Language="VB" %>
<script runat="server">
</script>
<html>
<head>
<title>Compare Validator - VB.NET</title>
</head>
<body>
<form runat="server">
Enter a First Value:
<asp:textbox id="firstvalue" runat="server">
</asp:textbox>
<br/>
Enter a Second Value:
<asp:textbox id="secondvalue" runat="server">
</asp:textbox>
<br/>
<asp:CompareValidator id="cv" runat="server"
Display="static" Operator="LessThan"
Type="Integer" ControlToCompare="firstvalue"
ErrorMessage="oops! Error occured"
ControlToValidate="secondvalue">
</asp:CompareValidator>
</form>
</body>
</html>

The above listing returns the text specified in the ErrorMessage property, if the value of the first textbox is less than that of the second one (See Figure 2). You can also compare two strings by setting the Type property to String and by setting the Operator to Equal.

validation_p1_2.jpg

Click here for larger image

CustomValidator

With the help of the Custom Validator control, you can write your own functions and use them for performing validations in Web Forms. These functions are similar to that of JavaScript and VBScript functions.

<script runat="server">
Sub ServerValidate (sender As Object, _
value As ServerValidateEventArgs)
Dim num As Int32 = Int32.Parse(value.Value)
If num Mod 2 = 0 Then
value.IsValid = True
Exit Sub
End If
value.IsValid = False
End Sub
</script>

Finally, you should integrate the above function with a WebForm control via ClientValidationFunction and ServerValidationFunction properties as shown in listing shown below:

<asp:TextBox id=Text1 runat="server" />
<asp:CustomValidator id="CustomValidator1" runat="server"
ControlToValidate="Text1" OnServerValidate="ServerValidate"
Display="Static" Font-Name="verdana" Font-Size="8pt" foreColor ="blue"
ErrorMessage = "Not an even number">
</asp:CustomValidator>

You have to specify a client-side or server-side function, which will contain the logic behind the validation using the OnServerValidate property. If there are any parameters, you should also specify those with this function. You should be aware that validations performed on the client's computer require no round trip to server and hence reducing the valuable online time of users.

RangeValidator

This control is used to accept a range of values. For instance, you can employ this validation control, if a user should have to input values within a range such as from 1 to 100 or from 50 to 150. It accepts two important properties, MinimumValue and MaximumValue, and also the Type property. The listing shown below illustrates the functionality of this control: 

<%@ Page Language="VB" %>
<script runat="server">
</script>
<html>
<head><title> Range Validator - VB.NET</title>
</head>
<body>
<form runat="server">
<p>
<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
</p>
<p>
<asp:RangeValidator id="RangeValidator1"
runat="server"
ErrorMessage="Please enter a number between 1 and 100"
ControlToValidate="TextBox1"
MinimumValue="1" MaximumValue="100"
Display="Dynamic" Type="Integer">
</asp:RangeValidator>
</p>
</form>
</body>
</html>

In this article, you learned how to perform validations using CompareValidator, CustomValidator and RangeValidator Controls. In the next part of this article, I'll examine the usages of other three controls.

About the Author

Anand Narayanaswamy (Microsoft MVP) works as an independent consultant and runs NetAns Technologies (http://www.netans.com) which provides affordable web hosting services for the community. Anand also runs LearnXpress.com (http://www.learnXpress.com) and Dotnetalbum.com (http://www.dotnetalbum.com) and regularly contributes articles, product and book reviews for various websites. He can be reached at ananddotnet@yahoo.co.in
 

Struts2-注解配置 validations

任意一个XML配置的validator都有一个相应的注解。每一个注解的属性都和XML的配置很相似。还有些注解可以用来把一个类定义为使用基于注解的验证,或是配置自定义的validator,还可以把一个属...
  • u011257574
  • u011257574
  • 2015年04月18日 17:13
  • 624

[ASP.NET学习笔记之二十]ASP_NET 2.0 中web part使用指南

ASP.NET 2.0中使用WebPart系列控件WebPart系列控件的布局在现在的网站设计中,更强调的是用户的个性化设置,让用户可以自由的设置符合自己喜好的页面成为网站开发人员的头号难题,不过现在...
  • lne818
  • lne818
  • 2006年08月25日 09:30
  • 1133

struts2 @Validations 注解的bug和缺陷

struts2 @Validations 注解的bug和缺陷
  • jiangshanwe
  • jiangshanwe
  • 2016年12月22日 11:45
  • 365

Coding for NEON - Part 1: Load and Stores

原文地址:http://community.arm.com/groups/processors/blog/2010/03/17/coding-for-neon--part-1-load-and-sto...
  • yazhouren
  • yazhouren
  • 2014年06月17日 10:19
  • 574

Performing stop of activity that is not resumed:

Performing stop of activity that is not resumed: {com.mobint.hololauncher/com.mobint.hololauncher.La...
  • wolfking0608
  • wolfking0608
  • 2017年08月21日 20:12
  • 489

Asp.net Basic Part(1)

Asp.net Basic Client ID mode : have different options can set web.config file .   Page Life cycle ...
  • csharp25
  • csharp25
  • 2013年10月23日 22:14
  • 861

Asp.net Configuration Part(1)

Asp.netConfiguration                                                        Global asax   ...
  • csharp25
  • csharp25
  • 2013年10月23日 22:20
  • 828

orcad中的警告Warning [ALG0016] Part Name 《》 is renamed to 《》解决

建立的part在library中为max3222-so20,但是在原理图中的元件下方的value为sp3222-so20, 生成网表时ORCAD识别的partname变成了max3222_so2...
  • sunheshan
  • sunheshan
  • 2014年04月27日 16:19
  • 3168

Coding for NEON - Part 1: load and stores

ARM 的 NEON技术是一种64/128位的混合 SIMD (single instruction multi-data, 多数据操作单指令)构架,是为多媒体和信号处理应用而设计,包括视频编解码,3...
  • opentld
  • opentld
  • 2013年10月10日 10:04
  • 1997

Django学习记录之Django 1.8 教程(我只是官网的搬运工)Tutorial Part 1

Part 1 第一步:创建项目 (确保你path 包含django)$django-admin startproject mysite(mysite为你的项目名字)这将会创建一个项目在你的当前目录...
  • Z_LiT0
  • Z_LiT0
  • 2015年11月30日 18:26
  • 268
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Performing Validations with ASP.NET - Part 1
举报原因:
原因补充:

(最多只允许输入30个字)