Search code examples
jqueryasp.netmaster-pages

Allow only text using jQuery in master page


I have created a label and textbox called signed by.

Here is my asp.net code:

<label>Signed By</label>
<div>
<asp:TextBox ID="txtSigned" class="form-control" runat="server"></asp:TextBox></div>

Here is my jQuery code:

$("#txtSigned").keypress(function(event){
 var inputValue = event.which;
 if(!(inputValue >= 65 && inputValue <= 120) && (inputValue != 32 && inputValue != 0)) { 
event.preventDefault(); 
}
});

So the user should enter text only in this textbox and numbers should not be allowed.


Solution

  • Get ClientID for the asp:TextBox and on key pressed, check if it matches the regex specificed (only letters, upper- and lowercase) and possibly deny if not:

    $("#<%=txtSigned.ClientID%>").on('keypress', function (event) {
        var regex = new RegExp("^[a-zA-Z]+$");
        var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
        if (!regex.test(key)) {
           event.preventDefault();
           return false;
        }
    });