Every developer needs to use letter validation in input fields on the client side, in other words the client wants that 3 input fields should only have letters and no end-user can fill in a value other than letters, like numbers, special characters and so on. In that case you can use JavaScript to disable the use of unwanted keys via the "onkeypress" event.
Some input fields like Name, Father's Name and Mother's Name and so on needs this kind of validation.
Note: I am assuming that a "space" may be used for the preceding kinds of fields.
To create a sample to explain such implementation, I will use the following procedure.
Step 1
Create an ASP.Net Empty Website named "My Project".
Step 2
Add a new web form named "Default.aspx" into it.
Step 3
Add a "TextBox" control for Name in the page named "Default.aspx" .
Step 4
Write a function in JavaScript that will get the ASCII code of the key that will be pressed by the user and will return "true" if it is a letter or space otherwise "false".
- function ValidAlphabet() {
-
- var code = (event.which) ? event.which : event.keyCode;
-
- if ((code >= 65 && code <= 90) ||
- (code >= 97 && code <= 122) || (code == 32))
- { return true; }
- else
- { return false; }
- }
Note:
- The ASCII codes of uper-case letters lies between 65 and 90.
- The ASCII codes of lower-case letters lies between 97 and 122.
- The ASCII code of space is 32.
Step 5
Now to call the function of JavaScript on the "onkeypress" event of TextBox.
- <asp:TextBox ID="txtName" runat="server"
- onkeypress="return ValidAlphabet()">
- </asp:TextBox>
Conclusion
In this article, I have described how to limit the user to typing only letters and I hope it will be beneficial for you.