Javascript Character input restriction script, with length limiter


/ Published in: JavaScript
Save to your folder(s)

Restricts the characters that are entered into a textbox. Also limits the length of the value to 5.


Copy this code and paste it in your HTML
  1. function inputLimiter(e, allow, value) {
  2. var AllowableCharacters = '';
  3. if (allow == 'Letters') { AllowableCharacters = ' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; }
  4. if (allow == 'Numbers') { AllowableCharacters = '1234567890'; }
  5. if (allow == 'NameCharacters') { AllowableCharacters = ' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-.\''; }
  6. if (allow == 'NameCharactersAndNumbers') { AllowableCharacters = '1234567890 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-\''; }
  7. var k;
  8. k = document.all ? parseInt(e.keyCode) : parseInt(e.which);
  9. if (k != 13 && k != 8 && k != 0) {
  10. if ((e.ctrlKey == false) && (e.altKey == false)) {
  11. return ((AllowableCharacters.indexOf(String.fromCharCode(k)) != -1) && (value.length < 5));
  12. } else {
  13. return true;
  14. }
  15. } else {
  16. return true;
  17. }
  18. }
  19.  
  20. <input type="text" onkeypress="return inputLimiter(event,'Numbers', this.value)" />

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.