Performing Validations with ASP.NET -- Part 1 of 2

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 are no proper error handling techniques employed on the server-side script. It is here that the usage of validations should come into the picture.

Validation means checking for the 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 and 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: client-side and server-side. While client-side validations can be performed by 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. Because VBScript won't work with Netscape browsers, 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 such as 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 such as TextBox, Dropdownbox, ListBoxes, and so forth. Even though there are wide ranges of controls for validation, it is up to you to decide which control to use. It also depends 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, and so forth) and Type property indicates the data type of the values like Integer, string, and the like.

To illustrate, copy or enter the code in Listing 1 and save the file with the 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, you need not worry about giving extensions, setting the language, and so on. The tool does all the work for you. It also includes a built-in server, which can be activated upon pressing the F5 key. You also can 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.

Figure 1



Click here for larger image

Listing 1

[Visual Basic .NET]

<%@ 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 occurred"
      ControlToValidate="secondvalue">
      </asp:CompareValidator>
    </form>
</body></html>

[C#]

<%@ Page Language="C#" %>
<script runat="server">
</script>
<html>
<head><title> Compare Validator - C#</title>
</head>
<body>
  <form runat="server">
      <p>
        Enter a First Value:
        <asp:TextBox id="txtFirstvalue" runat="server">
</asp:TextBox>
      </p>
      <p>
        Enter a Second Value:
        <asp:TextBox id="txtSecondvalue" runat="server">
</asp:TextBox>
      </p>
      <p>
<asp:CompareValidator id="cv" runat="server"
ErrorMessage="Oops! Error occurred"
Operator="LessThan"
Type="Integer"
ControlToValidate="txtSecondvalue"
ControlToCompare="txtFirstvalue">
</asp:CompareValidator>
      </p>
</form>
</body>
</html>

Listing 1 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.

Figure 2



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.

Listing 2

[Visual Basic .NET]

<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>

[C#]

<script runat="server">

bool  ServerValidate (sender As Object,
                      value As ServerValidateEventArgs)
{

  int num As Int32 = Int32.Parse(value.Value)

  If num % 2 = 0 
  {
      value.IsValid = True
   }
   value.IsValid = False
}

</script>

Finally, you should integrate the preceding function with a WebForm control via ClientValidationFunction and ServerValidationFunction properties, as shown in Listing 3.

Listing 3

<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. Listing 4 illustrates the functionality of this control.

Listing 4

[Visual Basic .NET]

<%@ 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>

[C#]

<%@ Page Language="C#" %>
<script runat="server">
</script>
<html>
<head><title> Compare Validator - C#</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>

Next Time...

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 is a Microsoft MVP (Microsoft Most Valuable Professional) who works as a freelance Web/Software developer and technical writer. He runs and maintains learnxpress.com, and provides free technical support to users. His areas of interest include Web development, Software development using Visual Basic, and in the design and preparation of courseware, technical articles, and tutorials.

You can contact Anand at anandnswamy@rediffmail.com.



About the Author

Anand Narayanaswamy

Anand Narayanaswamy (Microsoft MVP) is a freelance writer for Developer.com and Codeguru.com. He works as an independent consultant and runs NetAns Technologies (http://www.netans.com)which provides affordable web hosting services. He is the author of Community Server Quickly (http://www.packtpub.com/community-server/book). Anand also runs LearnXpress.com (http://www.learnXpress.com) and Dotnetalbum.com (http://www.dotnetalbum.com) and regularly contributes product and book reviews for various websites. He can be reached at ananddotnet@yahoo.co.in

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • Due to internal controls and regulations, the amount of long term archival data is increasing every year. Since magnetic tape does not need to be periodically operated or connected to a power source, there will be no data loss because of performance degradation due to the drive actuator. Read this white paper to learn about a series of tests that determined magnetic tape is a reliable long-term storage solution for up to 30 years.

Most Popular Programming Stories

More for Developers

RSS Feeds