Click here to Skip to main content
15,868,016 members
Articles / Web Development / ASP.NET
Tip/Trick

Allow only Numeric values in ASP Text box control using JavaScript

Rate me:
Please Sign up or sign in to vote.
4.82/5 (6 votes)
11 Feb 2012CPOL 67.5K   8   5
Allow only Numeric (either whole or decimal) values in ASP Text box control using JavaScript
This allows only numeric (either whole or decimal) values in ASP Textbox control using JavaScript using ASP textbox key down event to fire the JavaScript function.

Example

ASP.NET
<asp:TextBox ID="txtDaysOutLB" Text="" MaxLength="4" onkeydown="return jsDecimals(event);" Width="75px" runat="server"></asp:TextBox>

Javascript Function

JavaScript
function jsDecimals(e) {

    var evt = (e) ? e : window.event;
    var key = (evt.keyCode) ? evt.keyCode : evt.which;
    if (key != null) {
        key = parseInt(key, 10);
        if ((key < 48 || key > 57) && (key < 96 || key > 105)) {
            if (!jsIsUserFriendlyChar(key, "Decimals")) {
                return false;
            }
        }
        else {
            if (evt.shiftKey) {
                return false;
            }
        }
    }
    return true;
}

// Function to check for user friendly keys  
//------------------------------------------
function jsIsUserFriendlyChar(val, step) {
    // Backspace, Tab, Enter, Insert, and Delete  
    if (val == 8 || val == 9 || val == 13 || val == 45 || val == 46) {
        return true;
    }
    // Ctrl, Alt, CapsLock, Home, End, and Arrows  
    if ((val > 16 && val < 21) || (val > 34 && val < 41)) {
        return true;
    }
    if (step == "Decimals") {
        if (val == 190 || val == 110) {  //Check dot key code should be allowed
            return true;
        }
    }
    // The rest  
    return false;
}

License

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


Written By
Web Developer Mahindra Logisoft Business Solution Limited, Chenn
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionAllow only numeric values in ASP Text box control with javascript Pin
Member 112042923-Nov-14 18:58
Member 112042923-Nov-14 18:58 
QuestionIT solved my problem thanks!!! Pin
Member 365210621-Nov-13 3:32
Member 365210621-Nov-13 3:32 
QuestionVery helpful but... Pin
dstamm5-Oct-13 8:05
dstamm5-Oct-13 8:05 
GeneralMy vote of 4 Pin
coolnavjot312-Jun-13 23:11
coolnavjot312-Jun-13 23:11 
GeneralMy vote of 5 Pin
NastaranZ18-Apr-13 23:04
NastaranZ18-Apr-13 23:04 

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.