Click here to Skip to main content
15,889,116 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
How to restrict special characters and spaces in textbox via javascript?
Posted
Updated 20-Nov-21 3:51am

Try this

XML
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript">
        function blockSpecialChar(e) {
            var k = e.keyCode;
            return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8   || (k >= 48 && k <= 57));
        }
    </script>
</head>
<body>
    <form id="frm" runat="server">
      <input type="text" name="name"  onkeypress="return blockSpecialChar(event)"/>
    </form>
</body>
</html>
 
Share this answer
 
Comments
Karthik_Mahalingam 4-Feb-14 4:25am    
use this --> var k = e.keyCode == 0 ? e.charCode : e.keyCode;
for browser compatibility.
checkSpcialChar function will restrict the special characters in the input box. We need to pass the event as a parameter for that function. We also change keycodes to allow or disallow more keys.

HTML
<html>
   <head>
      <script type="text/javascript">
         function checkSpcialChar(event){
            if(!((event.keyCode >= 65) && (event.keyCode <= 90) || (event.keyCode >= 97) && (event.keyCode <= 122) || (event.keyCode >= 48) && (event.keyCode <= 57))){
               event.returnValue = false;
               return;
            }
            event.returnValue = true;
         }
      </script>
   </head>
   <body>
      <form id="form1">
        <div>
            <input type="text" name="txtInput" id="txtInput" value="" onkeypress="return checkSpcialChar(event)">
        </div>
     </form>
   </body>
</html>

For more details please refer this link
 
Share this answer
 
function ValidateString(e) {
var k;
document.all ? k = e.keyCode : k = e.which;
return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
}
 
Share this answer
 
<input class="form-control" type="text" placeholder="Enter Your Store Name"
id="shop_name" onkeyup="check_shopname()" required
onkeypress="return /[0-9a-zA-Z]/i.test(event.key)" name="shop_name"
autocomplete="off">
HTML

 
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