Click here to Skip to main content
15,881,938 members
Articles / Web Development / XHTML

NumericTextBox for ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.38/5 (6 votes)
9 Oct 2007CPOL2 min read 56.9K   935   40   11
An ASP.NET control that allows users to enter only numbers.

Screenshot - preview.jpg

Introduction

All applications must be "stupids-proof", so we are creating controls that check user's input, and this is one of them. On this website, I found only a solution for Windows Forms, so I'm presenting my solution for ASP.NET.

In the beginning, there was an idea of a control with these abilities:

  • Optional entering negative numbers
  • Optional entering decimal numbers or integers
  • Choose or load the decimal separator automatically from locale settings
  • Handle Ctrl + V
  • Cross-browser compatibility

Solution - Points of Interest

  • Handling all characters - in the end, I chose the "onkeypress" event, because if the function which is fired on this event returns false, the character will not be inserted into the textbox.
  • Filtering characters - All characters have a keyCode, so I had to make a list of the allowed characters (numbers inserted by numpad buttons have different codes than numbers inserted by the top line of a keyboard); also functional keys like Shift, BackSpace, Delete, and arrows must be allowed - just a few minutes of testing.
  • Optional minus sign - The minus sign must be the first character of the value, so I had to check the cursor position - that means problems with compatibility; in the end, I solved it like this:
  • JavaScript
    function getCursorPosition(txt)
    {
        if(document.selection) // IE
                {
            txt.focus();
            var oSel = document.selection.createRange();
            oSel.moveStart('character', -txt.value.length);
            return oSel.text.length;
        }
        else(txt.selectionStart) // Firefox etc.
                    return txt.selectionStart;
    }
  • Optional decimal separator - which one? This control allows entering decimals or integers, but different countries use different decimal separators, so I made a function that loads the settings dynamically from the culture settings:
  • C#
    private char GetDecimalSeparatorFromLocale()
    {
        return (System.Globalization.CultureInfo.CurrentUICulture.
                    NumberFormat.NumberDecimalSeparator.ToCharArray())[0];
    }
  • The decimal separator must meet several conditions:
    • must not be the first character
    • must not follow a minus sign
    • there must be only one decimal separator in the value

    This "beautiful" code checks all of these conditions:

    JavaScript
    if(txt.value.replace("-", "").length > 0 && 
              getCursorPosition(txt) > 0 && 
              txt.value.indexOf(decimalSeparator) == -1 && decimals)
        return true;
    else
        return false;
    break;
  • Handling Ctrl + V - I tried many ways to solve this problem. In the end, the simplest one worked best. In the "onchage" event, a check function is fired. This function checks all characters to see if they are allowed or not, and leaves only numbers and optionally a minus sign and a decimal character.
  • JavaScript
    function CheckString(txt, negative, decimals, decimalSeparator) 
    {
        var res = ""; 
        var decimalSeparatorCount = 0;
        for(i = 0; i < txt.value.length; i++)
        { 
            if(i == 0 && txt.value.charAt(0) == "-" && negative) 
                res = "-";
            else 
            { 
                if(IsNumber(txt.value.charAt(i)))
                // IsNumber function returns true if the char is 0-9
                    res += txt.value.charAt(i); 
                else 
                {
                    if(txt.value.charAt(i) == decimalSeparator && 
                       decimalSeparatorCount == 0 && decimals)
                    { 
                        res += txt.value.charAt(i);
                        decimalSeparatorCount++;
                    }
                }
            }
        }
        txt.value = res;
    }
  • Cross-browser compatibility.
    • IE 6,7 have, as I mentioned, problems with getting the cursor position
    • Safari returns a different keyCode for functional keys - returns 0 for all keys, but codes for numbers and other disallowed characters work fine
    • Tested browsers: IE 6,7, Opera 9, Firefox 2, Safari for Windows beta 3, Netscape 8 (same as Firefox, it uses the Gecko engine)

Using the Code

Using this code is simple because it inherits the TextBox class, so you can use validators and access the value in the Text property.

HTML
<cp:NumericTextBox AllowNegative="true" AllowDecimals="true" 
                   runat="server" ID="NumericTextBox1" />

This control is mainly based on JavaScript, so it can be easily used in other platforms such as PHP, JSP, etc., as well as in ASP.NET; if you translate it, please let me know.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Barclays Capital
Czech Republic Czech Republic
- .NET Developer, currently working for Barclays Capital
- Student of Czech Technical University in Prague - Faculty of information technologies

Comments and Discussions

 
GeneralIncorect format Pin
foczka30-Nov-07 2:47
foczka30-Nov-07 2:47 
GeneralRe: Incorect format Pin
Lukas Holota30-Nov-07 8:07
Lukas Holota30-Nov-07 8:07 
GeneralCopy/Paste Pin
foczka30-Nov-07 2:46
foczka30-Nov-07 2:46 
GeneralRe: Copy/Paste Pin
Lukas Holota30-Nov-07 8:03
Lukas Holota30-Nov-07 8:03 
Generalgood job Pin
sgraf471123-Oct-07 6:26
sgraf471123-Oct-07 6:26 
AnswerRe: good job Pin
Lukas Holota5-Nov-07 2:28
Lukas Holota5-Nov-07 2:28 
GeneralUse TryParse Pin
Jacques Bourgeois16-Oct-07 5:31
Jacques Bourgeois16-Oct-07 5:31 
GeneralRe: Use TryParse Pin
Lukas Holota16-Oct-07 7:21
Lukas Holota16-Oct-07 7:21 
GeneralRe: Use TryParse Pin
Jacques Bourgeois16-Oct-07 8:03
Jacques Bourgeois16-Oct-07 8:03 
GeneralRe: Use TryParse Pin
Lukas Holota16-Oct-07 8:30
Lukas Holota16-Oct-07 8:30 
GeneralRe: Use TryParse Pin
Jacques Bourgeois16-Oct-07 11:12
Jacques Bourgeois16-Oct-07 11:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.