Microsoft & .NETASPPerforming Validations with ASP.NET - Part 1 of 2

Performing Validations with ASP.NET – Part 1 of 2

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

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.

Figure 1

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 occured" 
      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 occured" 
Operator="LessThan" 
Type="Integer" 
ControlToValidate="txtSecondvalue" 
ControlToCompare="txtFirstvalue">
</asp:CompareValidator>
      </p>
</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.

Figure 2

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

# # #

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories