65.9K
CodeProject is changing. Read more.
Home

TextBox which accepts only numbers

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.06/5 (12 votes)

Jul 15, 2005

viewsIcon

177803

downloadIcon

3234

An article on how to allow users to enter only numbers in a TextBox.

Introduction

In this example, I'll show you how to extend ASP.NET textbox so that it accepts only numbers as input. Users will not be allowed to enter anything other than numbers in the textbox.

Using the code

Well, the process of doing this is quite simple and straightforward. The entire job is done in the Jscript procedure which handles the textbox's OnKeyPress event. Here are the steps involved to accomplish this:

  1. I have created is a simple Jscript procedure 'FilterNumeric()' which filters users keyboard entries on OnKeyPress event. Anything other than numbers, and '-', '.' are ignored.
  2. The procedure is registered on the page.
    Page.RegisterClientScriptBlock ("FilterNumeric",
                                     GetNumberValidatorScript());
  3. I have added an extra attribute to txtNumber control to handle the event OnKeyPress().
    txtNumber.Attributes.Add ("onkeypress", "FilterNumeric()");

I have added a RegularExpressionValidator to validate user entries on the server side. It uses the following expression:

(^[-]?[1-9]\d+$)|(^[-]?[1-9]$)|(^0$)|(^[-]?[1-9]\d+\.\d$)|(^[-]?[0-9]\.\d$)

and it allows: {123134456;4341643.2}.

Hope it helps someone!