JQuery to allow only alphabets, numeric and forward slash in TextBox



I have a text field in ASP.NET and i want to allow only alphanumeric and forward slash (/) keys in that. I tried the following code,

function jsCheckInput(e) {
    var evt = (e) ? e : window.event;
    var key = (evt.keyCode) ? evt.keyCode : evt.which;
    if (key != null) {
        key = parseInt(key, 10);
        if (key < 47 || (key > 57 && key < 65) || (key > 90 && key < 97) || key > 122) {
            if (!jsIsUserFriendlyChar(key)) {
                return false;
            }
        }
        else {
            if (evt.shiftKey) {
                return true;
            }
        }
    }
    return true;
}

function jsIsUserFriendlyChar(val) {
    // 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;
    }
    return false;
}

In the web forms page i added like below,

<asp:TextBox ID="text_value" CssClass="textbox" onkeydown="return jsCheckInput(event);" runat="server"></asp:TextBox>

Here i am able to enter alphabets and numbers but i am not able to enter the value /. I have enabled the shift key so i can give shift + ? to enter the forward slash. Also another problem is when i press shift + any numeric key the special characters there like ! @ # $ % ^ & * ( ) ... are also coming in tet field. What am i doing wrong here?

Answer

SOLUTION

Finally found a solution as below,

function jsCheckInput(e, t) {
    try {
        if (window.event) {
            var charCode = window.event.keyCode;
        }
        else if (e) {
            var charCode = e.which;
        }
        else { return true; }
        if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || (charCode > 46 && charCode < 58))
            return true;
        else if (jsIsUserFriendlyChar(charCode))
            return true;
        else
            return false;
    }
    catch (err) {
        alert(err.Description);
    }
}

This code works perfectly!!



Source: stackoverflow