Just launched the new site! Please excuse the mess as it is set up. Jump to: main content, navigation or the bottom.

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; } } }

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.


Comments (17)

What others have said about this post.

Got something to say?

Join the discussion! You know how these things work; enter your details and comments below and be heard.

If you have trouble reading the code, click on the code itself to generate a new random code.

Going up? Back to the top