Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Allow only Numeric values in ASP Text box control using JavaScript

4.82/5 (6 votes)
11 Feb 2012CPOL 68.6K  
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)