Introduction
During web development, nearly always, we need to provide input validation on even simple web forms. And in the case of the web, JavaScript is the best option available for validating input client-side. Server-side validation has its own use and it should be there but restricting user at the beginning is always needed. So, in this web development article, I am trying to present some requirements to limit the scope of the article, which are as follows:
- Only Numeric
Only numeric input should be allowed for some fields. So the user can't enter non-numeric characters in those particular fields. One step further, the user can't even copy & paste non-numeric input.
- Only Character
Limited to alphabetic character input only with an exception i.e. a space character that might be required even if we are entering only letters. Similarly, copy & paste must be restricted to other characters.
- Alphanumeric
Alphanumeric input allowed for certain fields but very restricted. Many of other or special characters shouldn't be allowed.
- Email validation
Validate against standard email format.
In order to apply these validations, we have a simple "Create User" form having the following fields:
- User Full Name: Only alphabetic characters and spaces.
- Username: Only alphabetic characters with dots (".") or dashes ("-").
- Password: Anything acceptable.
- Email: Standard Email format
- Mobile: Only numeric input
So, JavaScript functions are explained along with each field for understanding. Let's take each field one by one with its validation code.
First, a User Full Name field that will allow entering only alphabets and a space character. Alphabets can be upper or lower case letters. For example, my son's complete name will be "Muhammad Ahmad". So, the following field will take input accordingly.
The JavaScript function validating the input is:
- <asp:TextBox ID="txtFullName" onkeypress="return ValidateLettersWithSpaceOnly(event);"
- onPaste="return ValidateFullNamePaste(this);" MaxLength="50" runat="server">
- </asp:TextBox>
- function LettersWithSpaceOnly (evt)
- {
- evt = (evt) ? evt : event;
- var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
- ((evt.which) ? evt.which : 0));
- if (charCode > 32 && (charCode < 65 || charCode > 90) &&
- (charCode < 97 || charCode > 122)) {
- return false;
- }
- return true;
- }
- function ValidateFullNamePaste (obj)
- {
- var totalCharacterCount = window.clipboardData.getData('Text');
- var strValidChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ";
- var strChar;
- var FilteredChars = "";
- for (i = 0; i < totalCharacterCount.length; i++) {
- strChar = totalCharacterCount.charAt(i);
- if (strValidChars.indexOf(strChar) != -1) {
- FilteredChars = FilteredChars + strChar;
- }
- }
- obj.value = FilteredChars;
- return false;
- }

Join the conversation! Your thoughts help the community grow.