Numeric TextBox for ASP.NET

This example are shows how to extend textbox so it's only accepts number as an entry. User can't enter in the textbox anything else except number. Well the process of doing that is quite simple and straightforward. All the job is done in jscript procedure which handles textbox OnKeyPress event.

Here is all the steps necessary to accomplish:

  1. I have created a simple jscript procedure "FilterNumeric()" which filters users keybord entries on OnKeyPress event. Anything else except numbers, and "-", "." are ignored.
  2. Procedure is registered on the page.

    Page.RegisterClientScriptBlock ("FilterNumeric",GetNumberValidatorScript ());
  3. Added an extra attribute to txtNumber to handle event OnKeyPress( )

    txtNumber.Attributes.Add ("onkeypress", "FilterNumeric()");

Also I have additionally added a RegularExpressionValidator in order to validate users entry on server side. It uses the following expression: (^[-]?[1-9]\d+$)|(^[-]?[1-9]$)|(^0$)|(^[-]?[1-9]\d+\"+_strSeperator+@"\d$)|(^[-]?[0-9]\.\d$)

Hope that will be helpful for someone.

Up Next
    Ebook Download
    View all
    Learn
    View all