September 20, 2012

Using jQuery allowing Only Alphanumeric Characters in a Textbox


Requirement

Need to restrict the users by entering other than Alphanumeric Characters, if any user enters Non- Alphanumeric Characters then need to trim those Characters and display a message beside the respective textbox saying only Alphanumeric Characters are allowed…

 Solution:

We have many solutions but using jQuery is the best way to achieve, with this we can use more flexible and reliable Regular expression technology with jQuery to achieve the above requirement.

 Script Code:

 $(function () {

             $("#span_txtFirstName").hide();

            $("[id*='txtFirstName']").keyup(function () {

                $("#span_txtFirstName").hide();

                if (this.value.match(/[^a-zA-Z0-9 ]/g)) {

                    this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '');

                    $("#span_txtFirstName").toggle(500);

                }

            });

 
HTML Code:

<asp:TextBox ID="txtFirstName" runat="server" Width="200px" CssClass="styled_input"></asp:TextBox>

<span id="span_txtFirstName" class="RegistrationNumericDiv">oops! Only AlphaNumberic Charecters are Accepted.</span>

 
Explanation:

In the above HTML Code is the normal code as I used asp.Net TextBox control to present this demo, but we can use any technology here as our browser parser can understand only HTML tags so every technology has their own parser to parse their respective language code to HTML code. Next line we have a SPAN tag which is used to hold the message to the user whenever user types a non-alphanumeric character in the respective textbox and this SPAN tag hide/show will be handled in the given jQuery code itself.

As we can see we use the regular expression to validate each character enter by the user and if anything wrong we replace those character(s) with empty string (‘’) and we show the message by toggling the  SPAN tag..

That’s it we are done with our requirement J

Thank you

Happy Coding J

No comments:

Post a Comment