Only Alphabet | Only Number | No Special Character - Textboxes Javascript Keypress Code
Many times we need code urgently and we think about a place from where we can just copy & paste. This post is one of them. Here you can find code and working example of javascript code to restrict user input in textboxes. We are providing you with 4 types of textboxes and there's a link in the bottom from where you can get all the keycodes and adjust our JavaScript code as per your need if you want.
Only Alphabets Allowed Textbox:
Code:
function onlyAlphabets(e, t) { try { if (window.event) { var charCode = window.event.keyCode; } else if (e) { var charCode = e.which; } else { return true; } if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123)) return true; else return false; } catch (err) { alert(err.Description); } } //textbox's html
Only Number Allowed Textbox:
Code:
function onlyNumber(e, t) { try { if (window.event) { var charCode = window.event.keyCode; } else if (e) { var charCode = e.which; } else { return true; } if (charCode > 31 && (charCode < 48 || charCode > 57)) return false; else return true; } catch (err) { alert(err.Description); } } //textbox's html
No Special Characters Allowed, Just Alphabets & Numbers
Code:
function noSpecialCharacters(e, t) { try { if (window.event) { var charCode = window.event.keyCode; } else if (e) { var charCode = e.which; } else { return true; } if (charCode < 48 || (charCode > 57 && charCode < 65) || (charCode > 90 && charCode < 97) || charCode > 122) return false; else return true; } catch (err) { alert(err.Description); } } //textbox's html
No Special Characters Allowed, Just Alphabets & Numbers - With Spacebar
Code:
function noSpecialCharactersPlusSpace(e, t) { try { if (window.event) { var charCode = window.event.keyCode; } else if (e) { var charCode = e.which; } else { return true; } if ((charCode < 48 && charCode != 32) || (charCode > 57 && charCode < 65) || (charCode > 90 && charCode < 97) || charCode > 122) return false; else return true; } catch (err) { alert(err.Description); } } //textbox's html
However, the world is so big and everyone has their own requirements. So you can tweak this code just to suit your requirements. In keypress events we are just restricting user input on the basis of the key they pressed.
Here's a reference list of all the keycodes W3Schools Link.
Let us know for any help. We would be happy to help.
Comments
Post a Comment
Hey there, liked our post. Let us know.
Please don't put promotional links. It doesn't look nice :)