random1 Posted February 24, 2010 Share Posted February 24, 2010 I've looked through Javascript validation scripts but all the ones I've found cover validation upon submition. I'm looking at entry point protect against wrong chracters. E.g. - Preventing all characters from being entered except numbers. - Preveting all chracters except upper case and lower case letters - Requiring that the chracters enter match a pattern (e.g. DD-MM-YYYY) etc... (Yes I have PHP code after to check all field data, I just want some nice front-end validation to filter out the bad entry straight up) Any Ideas? Quote Link to comment Share on other sites More sharing options...
random1 Posted February 24, 2010 Author Share Posted February 24, 2010 I have found: http://www.qodo.co.uk/blog/javascript-restrict-keyboard-character-input/ Source: /* 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; } } } That pretty much works as I need it but: - It accepts invalid characters like % & * # and @ Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.