TOC

The community is working on translating this tutorial into Indonesian, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Validation:

Validation - CompareValidator

The CompareValidator might not be the most commonly used validator of the bunch, but it's still useful in some cases. It can compare two values, for instance the values of two controls. In the next example, I will show you a small example of how it can be used.

Small number:<br />
<asp:TextBox runat="server" id="txtSmallNumber" /><br /><br />
Big number:<br />
<asp:TextBox runat="server" id="txtBigNumber" /><br />
<asp:CompareValidator runat="server" id="cmpNumbers" controltovalidate="txtSmallNumber" controltocompare="txtBigNumber" operator="LessThan" type="Integer" errormessage="The first number should be smaller than the second number!" /><br />

As you see, we only use one validator to validate the two fields. It might seem a bit overwhelming, but it's actually quite simple. Like with the RequiredFieldValidator, we use the controltovalidate attribute to specify which control to validate. In addition to that, we specify a control to compare. The operator attribute specifies which method to use when comparing. In this case, we use the LessThan operator, because we wish for the first control to have the smallest value. We set the type to integer, because we want to compare integers. Dates, strings and other value types can be compared as well.

Now, try running the website, and test the two new fields. Here is what happens if you don't fill out the form correctly:

If you switch the numbers, you will see another cool thing about the ASP.NET validators and clientside scripting: Validation is also performed upon exiting the fields. If you don't want this, you can turn off clientside scripting with the enableclientscript attribute. You can also compare a field to a static value. To do this, remove the controltocompare attribute, and add the valuetocompare attribute.

However, as you may have noticed, the content of the two textboxes is not checked before comparing it. For instance, it would be possible to enter nothing, or enter a piece of text instead of a number. You should always consider this when using the CompareValidator. You can protect against empty fields with the RequiredFieldValidator, and you can protect against wrong values like text with for instance a RegularExpressionValidator, which we will show you how to use a bit later.

If the clientside validation is not working, the invalid form will be catched by our piece of code in the CodeBehind file, as shown with the RequiredFieldValidator. This is important.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!