I have a text field in ASP.NET and i want to allow only alphanumeric and forward slash (/) keys in that. I tried the following code,
JavaScript
x
31
31
1
function jsCheckInput(e) {
2
var evt = (e) ? e : window.event;
3
var key = (evt.keyCode) ? evt.keyCode : evt.which;
4
if (key != null) {
5
key = parseInt(key, 10);
6
if (key < 47 || (key > 57 && key < 65) || (key > 90 && key < 97) || key > 122) {
7
if (!jsIsUserFriendlyChar(key)) {
8
return false;
9
}
10
}
11
else {
12
if (evt.shiftKey) {
13
return true;
14
}
15
}
16
}
17
return true;
18
}
19
20
function jsIsUserFriendlyChar(val) {
21
// Backspace, Tab, Enter, Insert, and Delete
22
if (val == 8 || val == 9 || val == 13 || val == 45 || val == 46) {
23
return true;
24
}
25
// Ctrl, Alt, CapsLock, Home, End, and Arrows
26
if ((val > 16 && val < 21) || (val > 34 && val < 41)) {
27
return true;
28
}
29
return false;
30
}
31
In the web forms page i added like below,
JavaScript
1
2
1
<asp:TextBox ID="text_value" CssClass="textbox" onkeydown="return jsCheckInput(event);" runat="server"></asp:TextBox>
2
Here i am able to enter alphabets and numbers but i am not able to enter the value /
. I have enabled the shift key so i can give shift + ?
to enter the forward slash. Also another problem is when i press shift + any numeric key the special characters there like ! @ # $ % ^ & * ( ) ...
are also coming in tet field. What am i doing wrong here?
Advertisement
Answer
SOLUTION
Finally found a solution as below,
JavaScript
1
21
21
1
function jsCheckInput(e, t) {
2
try {
3
if (window.event) {
4
var charCode = window.event.keyCode;
5
}
6
else if (e) {
7
var charCode = e.which;
8
}
9
else { return true; }
10
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || (charCode > 46 && charCode < 58))
11
return true;
12
else if (jsIsUserFriendlyChar(charCode))
13
return true;
14
else
15
return false;
16
}
17
catch (err) {
18
alert(err.Description);
19
}
20
}
21
This code works perfectly!!