20 November 2013

Explain about Compare validator in asp.net

In this post we will discuss about Compare validator in asp.net.

You can also check my previous articles on RequiredFieldValidator, RangeValidator, RegularExpressionValidator ,Validation summary examples in Asp.Net.

The CompareValidator control is used to compare the value of one input control to the value of another input control or to a fixed value.
Note : if the input control is empty,the validation will succed.use the requiredfieldvalidator control to make the field required.

Properties :
below operators using for compareValidator
1.equal
2.GreaterThan
3.GreaterThanEqual
4.LessThan
5.LessThanEqual
6.NotEqual
7.DataTypeCheck

Specifies the datatype of the values to compare.The types are ;

  • currency
  • Date
  • Double
  • Integer
  • String


Below is the full HTML code

<!DOCTYPE html>
<html>
<body>

<form runat="server">
<table border="0" bgcolor="#b0c4de">
   <tr style="vertical-align:top">
     <td colspan="4"><h4>Compare two values</h4></td>
   </tr>
   <tr style="vertical-align:top">
     <td><asp:TextBox id="txt1" runat="server" /></td>
     <td> = </td>
     <td><asp:TextBox id="txt2" runat="server" /></td>
     <td><asp:Button Text="Validate" runat="server" /></td>
   </tr>
</table>
<br>
<asp:CompareValidator
id="compval"
Display="dynamic"
ControlToValidate="txt1"
ControlToCompare="txt2"
ForeColor="red"
BackColor="yellow"
Type="String"
EnableClientScript="false"
Text="Validation Failed!"
runat="server" />
</form>

</body>
</html>


Declare two TextBox controls,one Button control and one compareValidator in an .aspx file.
If validation fails,the text " Validation Failed! " will be displayed in red on a yellow background in the CompareValidator control as shown in figure below :



No comments:

Post a Comment