Hello & Welcome
Portfolio of Web Designer, Stewart Orr
Welcome to the portfolio of Web Designer & Developer Stewart Orr - a passionate and highly enthusiastic designer from St. Albans in the UK with eight years of strong commercial experience and a healthy appetite for creating beautiful, accessible websites using Web Standards. Learn more about me, or get in touch.
Latest Blog Entry
JavaScript: Restrict keyboard character input
- May 27th, 2008
- Posted by Stewart
- Permalink
- 0 Comment(s)
If you want to improve your form inputs by restricting the characters the user enters, this function might come in handy. It restricts the keyboard input for a text field so that they can only enter the characters you want.
But why would you want to do this? Well it means your users cannot enter the wrong characters accidentally and have the form fail when it is validated. It also makes inputting data a little bit faster! It should not be used as the only method of validating your forms as the users can turn javascript off and enter whatever they like anyway, but it is a nice, lightweight little add-on for your forms.
You can add further restrictions by creating your own regular expressions at the top to restrict to email-only characters, telephone characters and more! If you are looking for something in particular, get in touch!
/* code from qodo.co.uk */
// create as many regular expressions here as you need:
var digitsOnly = /[1234567890]/g;
var integerOnly = /[0-9\.]/g;
var alphaOnly = /[A-Z]/g;
function restrictCharacters(myfield, e, restrictionType) {
if (!e) var e = window.event
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
// if they pressed esc... remove focus from field...
if (code==27) { this.blur(); return false; }
// ignore if they are press other keys
// strange because code: 39 is the down key AND ' key...
// and DEL also equals .
if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
if (character.match(restrictionType)) {
return true;
} else {
return false;
}
}
}
Download the example JavaScript: Restrict keyboard character input now!
