Javascript Regular Expression Allow Alphanumeric KeyUp

by aherrick 22. January 2010 04:13

Working on an application I needed to write a script to only allow Alphanumeric characters (Letters and Numbers only) for dynamic XML generation.  We wanted the solution to be smart enough that when the user is typing in a textbox, any character other than Alphanumeric is automatically removed while they are typing into the input.  Using a combination of jQuery and regular Javascript the solution becomes simple. 

Take a look at the Javascript used below.

    <script type="text/javascript">

        $(function() {

            $('#basicInput').keyup(function() {

                // cache input and value
                var input = $('#basicInput');
                var value = $('#value');

                // only allow letters, numbers, don't allow spaces
                var tempVal = input.val().match(/[A-Za-z0-9]+/g);
                tempVal = tempVal == null ? "" : tempVal.join("");

                // display formatted input
                input.val(tempVal);
                value.html(tempVal);
            });
        });
        
    </script>

First we attach a jQuery keyup event to the text input. We then get the value of the input and run it through a basic regular expression to get the match. We then update the input with the array of matched values.

Great! Check out the example page to see it in action!

Tags:



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen
Tweaked by ajondeck.NET

About the author

Andrew Herrick
I am a full time developer for Blue Horseshoe Solutions based out of Carmel, Indiana. I enjoy learning new technology and hope to give back with some of the cool things I pick up along the way.  Check me out on Stack Overflow!


Categories

None

Recent comments

Comment RSS

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in  anyway.

© Copyright 2008