Farmer
Farmer

Reputation: 11003

Accept just numbers on a TextBox ASP.NET

I have a TextBox & I want to accept just numbers in this TextBox when typing.

Thanks.

Upvotes: 0

Views: 6935

Answers (3)

Adam Nuttall
Adam Nuttall

Reputation: 477

If you are using the AjaxControlToolkit then consider the FilteredTextBox extender.

<ajaxToolkit:FilteredTextBoxExtender ID="ftbe" runat="server" TargetControlID="YourTextBoxID" FilterType="Numbers" FilterMode="ValidChars" />

Upvotes: 0

Kelsey
Kelsey

Reputation: 47766

I use the following client side code to do this:

jQuery.fn.ForceNumericOnly =
function()
{
    return this.each(function()
    {
        $(this).keydown(function(e)
        {
            var key = e.charCode || e.keyCode || 0;
            // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
            return (
                key == 8 || 
                key == 9 ||
                key == 46 ||
                (key >= 37 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105));
        })
    })
};

Then in my aspx page I attach it to my TextBox with:

$(document).ready(function()
{
    $("#<%= txtMyTextBox.ClientID %>").ForceNumericOnly();
});

This is a client side ONLY check so make sure to implement a server side check using like Int32.TryParse on your data as well to ensure that there is a number.

Upvotes: 2

womp
womp

Reputation: 116987

A great way to accomplish this is to use the MaskedEditExtender in the Ajax control toolkit.

The example page even has a demo for limiting user input to just numbers and number-related characters.

Upvotes: 1

Related Questions