开发者

Accept just numbers on a TextBox ASP.NET

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

Thanks开发者_运维问答.


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.


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.


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜