Easy JavaScript to Restrict Textbox Input

Want to use JavaScript to restrict the characters that can be input on a textbox?  It’s easy!

Here’s a very small function that will remove illegal characters, and replace spaces with hyphens.  I used on a textfield that was used as part of a url.

Javascript:

restrictAlias = function(o){
  var r = /[^A-Z|a-z|0-9|-]/g;
  o.value = o.value.replace(' ', '-');
  o.value = o.value.replace(r,'');
};
 

There’s two things going on here. First spaces are replaced with hyphens. Since I’m using this for a part of a url, I don’t want spaces and thier ugly ‘%20′ encoded counterparts, so I just replace them. It happens seamlessly for the user. Next I use a regular expression as a replace criteria to remove offending characters. More accurately, I remove characters that are not listed in the “good” list. You can replace the regular expression (var r) with anything that fits your needs.

Then you’ll want to call the function on the textfield’s ‘onKeyUp’ and ‘onBlur’ events. Whenever the user types a new key, or leaves the text field (ie, copy/paste) the illegal chars will be removed or substituted.

HTML:

<input id="text1" name="text1" type="text" 
       onkeyup="restrictAlias(this);validateAlias(this);" />

Here’s some additional regex links:

Regex Patterns

Javascript Regex Tester

No TweetBacks yet. (Be the first to Tweet this post)

Leave a Reply

You must be logged in to post a comment.