There is often a scenario where client want the user to enter only alphabets nothing else. Though the validations will fail at the Database level when there is data type mismatch. Like for example, we have a textbox for Age and user enter letters into it. The validation will surely fail as the datatype in table would be int/smallint.
So it is also wise enough to add validation at the Javascript level, so that when user tries to enter something absurd other than letters alert would come saying Please enter only alphabets.
This below snippet will surely be of help.
- <html>
- <head>
- <title>allwon only alphabets in textbox using JavaScript</title>
-
- </head>
- <body>
- <table align="center">
- <tr>
- <td>
- <input type="text" onkeypress="return allowOnlyLetters(event,this);" />
- </td>
- </tr>
- </table>
- </body>
- </html>
- <script language="Javascript" type="text/javascript">
-
- function allowOnlyLetters(e, t)
- {
- 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
- {
- alert("Please enter only alphabets");
- return false;
- }
- }
- </script>
Please use this easy & simple snippet and try out your validation.
Hope this helps .
Thanks