Click here to Skip to main content
15,887,596 members
Articles / Web Development / HTML
Tip/Trick

ASP.NET Textbox Remove Comma

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
6 Sep 2012CPOL1 min read 13.9K   1   1
Prevent users from entering comma

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.

C++
<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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
I am a software developer with a passion to develop innovative ideas.

Comments and Discussions

 
GeneralMy vote of 5 Pin
manojsawkar6-Sep-12 23:55
manojsawkar6-Sep-12 23:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.