ASP.NET CompareValidator - How to validate Data Type

Validate data type using CompareValidator
The CompareValidator class compares the value entered by the user in an input control with the value entered in another input control or with a constant value.

The following c# tutorial code demonstrates how we can validate a data type using CompareValidator. In this example code, we will validate the integer data type. We will check the user input an integer value for the age field or not using the CompareValidator.

The CompareValidator ControlToCompare property gets or sets the input control to compare with the input control being validated. This property value is a String which is the input control to compare with the input control being validated. The default value is Empty.

The c# developers have to use the ControlToCompare property to specify an input control, such as a TextBox control, to compare with the input control being validated.

The CompareValidator Operator property gets or sets the comparison operation to perform. This property value is one of the ValidationCompareOperator values. The default value is Equal.

The ValidationCompareOperator Enum specifies the validation comparison operators used by the CompareValidator control. In this example, we set this property value to DataTypeCheck. The DataTypeCheck is a comparison for data type only.

The CompareValidator Operator property throws ArgumentOutOfRangeException if the specified comparison operator is not one of the ValidationCompareOperator values. For the CompareValidator Type property value, we set the Integer to validate the data type.

<%@ Page Language="C#" %>
<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender,System.EventArgs e){
        Label1.Text = "Form Submited. Your value is Integer";

<html xmlns="">
    <head id="Head1" runat="server">
        <title>CompareValidator example: how to validate Data Type in</title>
        <form id="form1" runat="server">
                <asp:Label ID="Label1" runat="server" Font-Size="Larger" ForeColor="DarkCyan"></asp:Label>
                <br />

                <asp:Label ID="Label2" runat="server" Text="Age" AssociatedControlID="TextBox1"></asp:Label>
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" Text="*"></asp:RequiredFieldValidator>
                <asp:CompareValidator ID="CompareFieldValidator1" runat="server" ControlToValidate="TextBox1" Operator="DataTypeCheck" Type="Integer" ErrorMessage="Input valid age">
                <br />

                <asp:Button ID="Button1" runat="server" Text="Validate DataType" OnClick="Button1_Click" />
Related example