Accept only numbers by the TextBox in ASP.NET

January 31, 2014 0 Comments

If you want to do it in that your TextBox accept only number when user input in it. Use CompareField Validator for this type of problem, Normally we use CompareField Validator for password recheck. Today we use it for another purpose, now, take an example.

Accept Only integer type number by TextBox

Step-1 : Add webform into the project.
Step-2 : Take one TextBox and Button control onto the webform.
Step-3 : Also take one Required field and one compare field validator onto the web form.
Step-4 : Set Property of required field validator, these are

Text= "Required"

Step-5 : Set Property of CompareField Validator, these are

   Text= "Enter Only numbers"

Complete code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="">
<head runat="server">
    <form id="form1" runat="server">
        Enter age :
        <asp:TextBox ID="TextBox1" runat="server" Width="172px"></asp:TextBox>
&nbsp;<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
            ControlToValidate="TextBox1" Display="Dynamic" ForeColor="#CC0000">Required</asp:RequiredFieldValidator>

        <asp:CompareValidator ID="CompareValidator1" runat="server" 
            ControlToValidate="TextBox1" Display="Dynamic" ForeColor="#CC0000" 
            Operator="DataTypeCheck" Type="Integer">Enter Only numbers</asp:CompareValidator>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Submit" />

Code Generate the following Output

Accept only numbers by the TextBox in ASP.NET

Jacob Lefore

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard. Google