JQuery Allow only numeric characters or only alphabet characters in textbox
Posted by in Javascript April 7, 2012 Leave a comment

In this article, I will demonstrate how to allow user to input only numeric or only alphabet or only alphanumeric characters in a TextBox field by using JQuery. The program also prevents user from copying and pasting invalid characters into the TextBox.
About technical, I use regular expression to prevent unexpected characters in keyup event.

How to implement

++ Desgin HTML with 3 input text box fields :
1) Textbox 1 : Allow only Alphanumeric Characters
2) Textbox 2 : Allow only Numeric Characters
3) Textbox 3 : Allow only Alphabet Characters

<form id="form1" runat="server">
<div>
 
    Allow <strong>only Alphanumeric Characters</strong> in a TextBox
    <asp:TextBox ID="txtAlphaNumeric" runat="server"/>
    <br /><br />
 
    Allow <strong>only Numeric Characters</strong> in a TextBox      
      <asp:TextBox ID="txtNumeric" runat="server"/>
    <br /><br />
 
    Allow <strong>only Alphabet Characters</strong> in a TextBox      
    <asp:TextBox ID="txtAlphabet" runat="server"/>
</div>
</form>

++ Add JQuery library by including jquery-1.7.1.min.js to head of HTML :
Download JQuery library plugin here

<script type='text/javascript'
    src='Scripts/jquery-1.7.1.min.js'>
</script>

++ Add Javascript code to process textbox fields:

  • A regular expression /[^0-9]/g : find all characters that are not numbers
  • A regular expression /[^a-zA-Z]/g : find all characters that are not alphabets
  • A regular expression /[^a-zA-Z0-9 ]/g : find all characters that are not alphabets or numbers
  • If user enters a character matching with the expression, the character will be replaced with an empty string.

    <script type="text/javascript">
        $(function() {
            $('#txtNumeric').keyup(function() {
                if (this.value.match(/[^0-9]/g)) {
                    this.value = this.value.replace(/[^0-9]/g, '');
                }
            });
            $('#txtAlphabet').keyup(function() {
                if (this.value.match(/[^a-zA-Z]/g)) {
                    this.value = this.value.replace(/[^a-zA-Z]/g, '');
                }
            });
            $('#txtAlphaNumeric').keyup(function() {
                if (this.value.match(/[^a-zA-Z0-9]/g)) {
                    this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
                }
            });
        });
    </script>

    ++ Below is demontration image :

    Only allow numeric or alphabet or alphanumeric characters

    Only allow numeric or alphabet or alphanumeric characters