Enter only characters in textbox in ASP.Net

In this blog we will know, allow only characters in textbox in asp.net.

Method-1

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Enter_only_characters_in_textbox._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript" language="javascript">
    function character(e)
   {
    isIE = document.all ? 1 : 0
    keyEntry = !isIE ? e.which : event.keyCode;
    if (((keyEntry >= '65') && (keyEntry <= '90')) || ((keyEntry >= '97') && (keyEntry <= '122')) || (keyEntry == '46') || (keyEntry == '32') || keyEntry == '45')
    return true;
    else
    {
        return false;
    }
}
    </script> 
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox ID="txtName1" runat="server" onkeypress="return character(event)" ></asp:TextBox>
    </div>
    </form>
</body>
</html> 

Method-2

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Enter_only_characters_in_textbox.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript" language="javascript">
    function character(evt)
    {
    evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
    ((evt.which) ? evt.which : 0));
    if (charCode > 31 && (charCode < 65 || charCode > 90) &&
    (charCode < 97 || charCode > 122)) {
     alert("Enter only characters");
     return false;
    }
     return true;
    }
    </script> 
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="text" onkeypress="return character(event)" />
    </div>
    </form>
</body>
</html>

Ebook Download
View all
Learn
View all