Monday, 5 August 2013

CompareValidator in asp.net

CompareValidator most commonly used validator of  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:
<asp:TextBox runat="server" id="txtSmallNumber" />
Big number:
<asp:TextBox runat="server" id="txtBigNumber" />
<asp:CompareValidator runat="server" id="cmpNumbers" type="Integer"
controltovalidate="txtSmallNumber" controltocompare="txtBigNumber" operator="LessThan"
errormessage="The first number should be smaller than the second number!" />
 
Now, im am run the website, and test the two new fields. Here is what happens if you don't fill out the form correctly:
 






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. RegularExpressionValidator, which we will show you how to use a bit later. 

No comments:

Post a Comment