Step 1:- JavaScript Code
<script type="text/javascript">
function OnlyAlphaNumericCharacter(evt) {
var keyCode
= (evt.which) ? evt.which : evt.keyCode
if (evt.ctrlKey
|| evt.altKey) {
return false;
}
if ((keyCode
> 47 && keyCode < 58) || (keyCode > 95 && keyCode <
106) || (keyCode > 64 && keyCode < 91) || (keyCode > 96
&& keyCode < 123) || (keyCode > 36 && keyCode < 41)
|| keyCode == 8 || keyCode == 9) {
return true;
}
return false;
}
</script>
Step 2:- Design Page
<table style="border: 1px; width: 500px;">
<tr>
<td style="width: 200px;">
<label for="alphaNumeric">Alpha
Numeric:</label>
</td>
<td style="width: 200px;">
<asp:TextBox ID="alphaNumeric" runat="server" placeholder="Enter
Name" ClientIDMode="Static" onkeypress="return
ValidateAlphaNumericCharacter(event);" onkeyup="return
ValidateAlphaNumericCharacter(event);" onkeydown="return
ValidateAlphaNumericCharacter(event);"></asp:TextBox>
</td>
</tr>
</table>
Step 3:- Complete Code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="
Default.aspx.cs" Inherits="Demo.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Allow
only AlphaNumeric Character</title>
<script type="text/javascript">
function OnlyAlphaNumericCharacter(evt) {
var keyCode
= (evt.which) ? evt.which : evt.keyCode
if (evt.ctrlKey
|| evt.altKey) {
return false;
}
if ((keyCode
> 47 && keyCode < 58) || (keyCode > 95 && keyCode <
106) || (keyCode > 64 && keyCode < 91) || (keyCode > 96
&& keyCode < 123) || (keyCode > 36 && keyCode < 41)
|| keyCode == 8 || keyCode == 9) {
return true;
}
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style="border: 1px; width: 500px;">
<tr>
<td style="width: 200px;">
<label for="alphaNumeric">Alpha
Numeric:</label>
</td>
<td style="width: 200px;">
<asp:TextBox ID="alphaNumeric" runat="server" placeholder="Enter
Name" ClientIDMode="Static" onkeypress="return
ValidateAlphaNumericCharacter(event);" onkeyup="return
ValidateAlphaNumericCharacter(event);" onkeydown="return
ValidateAlphaNumericCharacter(event);"></asp:TextBox>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Note:-
I am allowing to performance Tab, Backspace, Left Arrow Key, Up
Arrow Key, Right Arrow Key
& Down Arrow Key in the textbox.
If you don’t need it, remove the highlighted condition in the
JavaScript.
i.e.
|| (keyCode > 36 && keyCode < 41)
|| keyCode == 8 || keyCode == 9)
Arrow Key Condition - (keyCode
> 36 && keyCode < 41)
Backspace Condition - keyCode == 8
Tab Condition - keyCode == 9
If you need to allow Space, just add the keyCode == 32 in JavaScript condition.
So, after adding it your condition look like –
if ((keyCode > 47 && keyCode <
58) || (keyCode > 95 && keyCode < 106) || (keyCode > 64
&& keyCode < 91) || (keyCode > 96 && keyCode < 123) || (keyCode > 36
&& keyCode < 41) || keyCode ==
32 || keyCode == 8 || keyCode == 9)
{
return true;
}
return false;
Space
Condition - keyCode == 32
No comments:
Post a Comment