Introduction
This tip is about how we can prevent users from entering some characters like comma, a,b...etc.
Background
We can use two methods, either a client side method or a server side method. A client side method would be preferable because it is so fast, while the server side method needs postback.
Using the Code
We can use jquery and JavaScript for which first you add the reference of the jquery library.
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
Then we need to write code on .keypress
function. We use keyypress
function instead of keydown
and keyup
because if we use it, we can prevent from entering into the textbox
, i.e., the key press is being prevented when the user presses the key. But key down and key up functions allow the users to enter the value into the text box and then validate the entered value.
In keypress
event, we will not get the keyCode
instead we can use charcode
. keyCode
says something
about the actual keyboard key the user pressed, while charCode
gives the ASCII value of the resulting character. These
bits of information need not be the same; for instance, a lower case 'a
' and an upper case 'A
' have the same keyCode
,
because the user presses the same key, but a different charCode
because the resulting character is different.
if (e.charCode == 44 || e.which == 44) {
if ($.browser.msie) // for IE7
event.returnValue = false;
return false;
}
Here we evaluate which key is being pressed and take action accordingly.
**charCode
property indicates the Unicode for the key pressed. Use
String.fromCharCode(charCode)
to convert code to string.
NS/Firefox only.
List of Charcodes
32 [Spac]
33 !
34 "
35 #
36 $
37 %
38 &
39 '
40 (
41 )
42 *
43 +
44 ,
45 -
46 .
47 /
For getting the full code, check out my blog post here.