Whenever we create a contact form or user form. We want that no user should input a special character, because there may be a hacking script. Which can destroy or hack our database or project file.
In this blog post, we will learn how don’t allow special characters in textbox javascript. First, make a textarea in HTML.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Don't Allow Special Characters in Textbox Javascript</title>
</head>
<body>
<form id="frm" runat="server">
<textarea name="folderName" onkeypress="return blockSpecialChar(event)"></textarea>
</form>
</body>
</html>
Here I using onkeypress, The onkeypress
property of the GlobalEventHandlers
mixin is an event handler that processes keypress
events.
Javascript
<script type="text/javascript">
function blockSpecialChar(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));
}
</script>
Another method
<script type="text/javascript">
function blockSpecialChar(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>
Hope this code will be helpful for you.

Brijpal Sharma is a web developer with a passion for writing tech tutorials. Learn JavaScript and other web development technology.