What does it do?
This bit of Javascript watches what the user is entering on a form field and if they are entering characters that are not allowed, it prevents them from being added to help them get it right without any pain.
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.
// 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;
}
}
}