Understanding ASP.Net Validation Controls

Visited 1621 times | Submited on 2007-07-17 14:18:21

Finding input validation with ASP.Net a chore? In this article Armando gives us the low down on ASP.Net validation controls, along with helpful coding examples to get you started.In this article I want to share the logic behind ASP.Net validation controls with you. These controls come with the .NET framework. They perform validation on the client and server, meaning that in the remote case if the browser has no JavaScript support then the validation can only be performed on the server.

If you've never had experience with ASP.Net validation controls then this article will shed light on them and teach you everything you need to know about them.

The Syntax Of Validation Controls

The syntax of these validation controls is very simple and you don't have to deal with complicated JavaScript validation code. All of the Validation controls inherit from the Label control.

Here are some of their most important properties:

  • ControlToValidate: The ID of the control that this validator validates.
  • Display: Has three possible values: Dynamic, Static and None. Dynamic means that the space the control uses isn’t reserved for the control. Static means that the space it uses is always reserved for the control, and lastly None makes the control invisible.
  • EnableClientScript: This means that the validation occurs on the server (the default is true).
  • Text: Is displayed when the validation fails; it’s often used to put an asterisk or an icon next to the error and for displaying the error message in a validation summary.

Remember that if you have VS.NET you don't need to hard code all of these properties; just open the properties dialog in Visual Studio using the design mode.

The simplest control is the RequiredValidator Control, which as the name implies, looks for the specified control to validate and checks if it contains a specific value.

It compares the value of a control with its InitialValue property (which defaults to an empty string). If the two values are the same then it evaluates to false. If the InitialValue property isn't an empty string, a blank entry would be valid, so the simplest way to avoid this is with the use of two controls.

Here's an example of using the control with a Textbox:

Email: <asp: Textbox runat="Server" ID="email" />
<asp:RequiredFieldValidator runat="Server" ControlToValidate="email" ErrorMessage="Please enter an email address" ID="emailReqValidator" />

The CompareValidator Control
The next control is CompareValidator, which you use to compare a control's value with a static value or another control's value. This control exposes four properties to define how the comparison is performed:

  • Type: Describes the type of data expected in the ControlToValidate.
  • Operator: Determines the type of operation the control is going to perform. A very important option is DataTypeCheck, which will be used to check if the value in the Type property is correct.
  • ControlToCompare: The ID of the control to compare with.
  • ValueToCompare: The static value to compare with the ControlToValidate.

Remember that only one instance of the last two properties can be given to a single control.

Here's an example that uses the CompareValidator control. We are using it to make sure the first textbox has an integer value, and then we use it to ensure that the first textbox value is greater than the second.

Here's the code:

<asp:TextBox id="Num1" runat="server"></asp:TextBox>
<asp:TextBox id="Num2" runat="server"></asp:TextBox>

<asp:CompareValidator id="CompareValidator1" runat="server" ErrorMessage="You have to write an integer value" ControlToValidate="Num1" Type="Integer" Operator="DataTypeCheck"></asp:CompareValidator>

<asp:CompareValidator id="CompareValidator2" runat="server" ErrorMessage="The 1st value have to be greater than the 2nd" ControlToValidate="Num2" Type="Integer" ControlToCompare="Num1" Operator="LessThan"></asp:CompareValidator>




The next control is RangeValidator, which is a little simpler than the CompareValidator control. This control simply checks that the value falls into a specific range.

This range is determined from the MaximumValue and MinimumValue properties; this control also contains the Type property, just like the CompareValidator control.

Here's an example of using the RangeValidator control to ensure that the value in the textbox falls between 100 and 300:

<asp:textbox id="weight" runat="server"></asp:textbox>

<asp:rangevalidator id="RangeValidator1" runat="server" ErrorMessage="Write a correct weight" ControlToValidate="weight" Type="Integer" MaximumValue="300" MinimumValue="100"></asp:rangevalidator>

The RegularExpressionValidator Control

The next Control is the RegularExpressionValidator control. This control makes use of regular expressions, which are a way of describing a string pattern. Regular expressions are out of the scope of this article, so we will bypass this control. Just remember that this control exposes the ValidationExpression property, where you can enter the RegularExpression you want to valid a control against.

There are going to be cases where you need a special way of validate some content: something that the .NET Framework can't offer to you. This is where CustomValidator control comes into play.

As the name implies, this control lets you write the logic for the validation of a control anyway you like. This control exposes an OnServerValidate event that you can use to tie the logic written on the server (such as a function) to the validation control, meaning that the validation will be performed on the server.

Both the server and client validation have to have specific formats. On the server side if you are using C# then the function must return a void and have two parameters: an object argument and a System.Web.UI.WebControls.Custom.ServerValidateEventArgs object.

Here's a function that checks if a number is a pair or not. As you can see, we don't perform any checking in the function about the type of data we are receiving in the argument, since we already saw how to accomplish this using the other Validation controls:

public void Doble(object sender, System.Web.UI.WebControls.ServerValidateEventArgs e)
{
try
{
if ((int.Parse(e.Value) % 2) == 0)
e.IsValid = true;
else
e.IsValid = false;
}
catch
{
e.IsValid = false;
}
}

Here you can see that we check if the modulus of the value being passed to the function – if the modulus is zero then it's a pair number. If anything goes wrong the catch block sets the IsValid property to false.

The only drawback to this method is that the validation is made on the server, so you need a roundtrip to the server each time you want to perform the validation. In order to avoid this, you have to code a client side version of our validation code using JavaScript.

A nicer control is the ValidationSummary control, which doesn't actually perform any validation – this control makes it possible to display all of the error messages in a single place, making a nice layout for your page.

By default all of the validation controls display their error message where the control is placed, so the ValidationSummary control serves as a way of organize the error messages of the controls. Remember, however, that by using the Text property of the controls, you can still mark an astricks in place where an error is and display a more detailed message in the summary control.

The summary control has different rendering options, such as a bulleted list, a single paragraph or a simple list. It also has the option to be displayed as a message box if JavaScript is enabled.

If you want to have code reusability in your applications, then you could create a control that contains a textbox for email, a RequiredFieldValidator control, and a RegularExpressionValidator control. You could then put this combination of controls in the VS.NET listbox and use it like a drag 'n drop control in your webforms.

Finally, remember to use the Page.IsValid property before performing any logic, as this property is set on a page when the page uses a validation control. After a PostBack event, this property will be set to true only if the page passed all of the validation logic required.

Conclusion 

As you can see, these new validation controls make our lives as .NET developer's a lot easier, saving us the time of creating validation code on both the server and the client.

Stay tuned for my next article about validation controls in which I will write about some problems I've been having when using several Postback methods in the same page. We will also build a control that inherits from some validation control classes.

Author: Armando Andrade
Source: devarticles.com



Add your comment

Name:(required)
E-mail address:(optional)
Comment:(required)
Repeat the number for validation: (required)

Browse by Tags:


Related Articles:

Text Link Ads

Statistics

Total 296 articles submitted
Latest submission at January 28, 2008 15:13

Feedback

Use this email below to send us your suggestions and feedback. We value your opinion.
info (at) theitarticles.com