JavaScript: Restrict keyboard character input

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.

How could this be used?

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 floatOnly = /[0-9\.]/g;
var alphaOnly = /[A-Za-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;
        }
    }
}

Updates

Updated 01/12/2009: As pointed out by JC, alpha wasn't allowing lowercase characters. This has been corrected. Also, integer is a whole number so should probably be labelled as float instead.


Download


Comments 19