Click here to Skip to main content
15,896,606 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am developing an application on ASP.NET in C# where I need to pass only text and numbers. Please help me to do this.
Thanks in advance.
Posted

1 solution

Try the following

XML
<asp:TextBox ID="txtCode" runat="server" Width="200px"                         Enabled="true" OnKeyPress="return restrictCharacters(event);"></asp:TextBox>


and the below JavaScript function

C#
function restrictCharacters(e) {
    if (!e) var e = window.event;
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;
    var character = String.fromCharCode(code);
    var alphaOnly = /[A-Za-z0-9]/g;
    if (code == 27) { this.blur(); return false; }
    if (!e.ctrlKey && code != 9 && code != 8 && code != 36 && code != 37 && code != 38 && (code != 39 || (code == 39 && character == "'")) && code != 40) {
        if (character.match(alphaOnly)) {
            return true;
        } else {
            return false;
        }
    }
}


Hope this helps.
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900