JavaScript - Validating Letters and Numbers

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:
  1. 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.
     
  2. 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.
     
  3. Alphanumeric
     
    Alphanumeric input allowed for certain fields but very restricted. Many of other or special characters shouldn't be allowed.
     
  4. 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.
  1. <asp:TextBox ID="txtFullName" onkeypress="return ValidateLettersWithSpaceOnly(event);"  
  2.             onPaste="return ValidateFullNamePaste(this);" MaxLength="50" runat="server">  
  3. </asp:TextBox> 
The JavaScript function validating the input is:
  1. function LettersWithSpaceOnly (evt)   
  2. {  
  3.             evt = (evt) ? evt : event;  
  4.             var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :  
  5.           ((evt.which) ? evt.which : 0));  
  6.             if (charCode > 32 && (charCode < 65 || charCode > 90) &&  
  7.           (charCode < 97 || charCode > 122)) {  
  8.                 return false;  
  9.             }  
  10.             return true;  
  11. }  
  12.    
  13. function ValidateFullNamePaste (obj)   
  14. {  
  15.             var totalCharacterCount = window.clipboardData.getData('Text');  
  16.             var strValidChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ";  
  17.             var strChar;  
  18.             var FilteredChars = "";  
  19.             for (i = 0; i < totalCharacterCount.length; i++) {  
  20.                 strChar = totalCharacterCount.charAt(i);  
  21.                 if (strValidChars.indexOf(strChar) != -1) {  
  22.                     FilteredChars = FilteredChars + strChar;  
  23.                 }  
  24.             }  
  25.             obj.value = FilteredChars;  
  26.             return false;  
Secondly, the Username/Login field will allow entering letter, dot (".") or dash ("-") characters.
  1. <asp:TextBox ID="txtUsername"   
  2. onkeypress="return ValidateUsernameOnly(event);"  
  3.               onPaste="return ValidateUsernamePaste(this);"   
  4. MaxLength="30" runat="server">  
  5. </asp:TextBox>   
  6.    
  7. function ValidateUsernameOnly(evt)   
  8. {  
  9.             evt = (evt) ? evt : event;  
  10.             var characterCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :  
  11.             ((evt.which) ? evt.which : 0));  
  12. if (characterCode > 31 && (characterCode < 65 || characterCode > 90) && (characterCode < 45 || characterCode > 46) &&  
  13. (characterCode < 97 || characterCode > 122) && (characterCode < 48 || characterCode > 57)) {  
  14.                 return false;  
  15.             }  
  16.             return true;  
  17.  }  
  18.    
  19. function ValidateUsernamePaste(obj)   
  20. {  
  21.             var totalCharacterCount = window.clipboardData.getData('Text');  
  22.             var strValidChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.";  
  23.             var strChar;  
  24.             var FilteredChars = "";  
  25.             for (i = 0; i < totalCharacterCount.length; i++) {  
  26.                 strChar = totalCharacterCount.charAt(i);  
  27.                 if (strValidChars.indexOf(strChar) != -1) {  
  28.                     FilteredChars = FilteredChars + strChar;  
  29.                 }  
  30.             }  
  31.             obj.value = FilteredChars;  
  32.             return false;  
  33.   } 
For the Email field, a standard email validation is applied but it's triggered on form submission.
  1. <asp:TextBox ID="txtEmail"   
  2. MaxLength="30" runat="server">  
  3. <asp:Button ID="btnSave" Text="Create User" runat="server"   
  4.  OnClientClick="validateEmail(this);" />  
  5.    
  6. function validateEmail(emailField)  
  7.  {  
  8.             var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;  
  9.             if (reg.test(emailField.value) == false) {  
  10.                 alert('Invalid Email Address');  
  11.                 return false;  
  12.             }  
  13.             return true;  
  14.         } 
And finally, numeric validation for a phone number field is as follows:
  1. <asp:TextBox ID="txtPhone"   
  2. onkeypress="return ValidateNumberOnly(event);"  
  3. onPaste="return ValidateNumberPaste(this);"   
  4. MaxLength="10" runat="server">  
  5.               </asp:TextBox>  
  6.    
  7. function ValidateNumberOnly()  
  8.  {  
  9. if ((event.keyCode < 48 || event.keyCode > 57))   
  10. {  
  11.        event.returnValue = false;  
  12. }  
  13. }  
  14.    
  15. function ValidateNumberPaste(obj)   
  16. {  
  17.             var totalCharacterCount = window.clipboardData.getData('Text');  
  18.               var strValidChars = "0123456789";  
  19.            var strChar;  
  20.                   var FilteredChars = "";  
  21.             for (i = 0; i < totalCharacterCount.length; i++) {  
  22.                 strChar = totalCharacterCount.charAt(i);  
  23.                 if (strValidChars.indexOf(strChar) != -1) {  
  24.                     FilteredChars = FilteredChars + strChar;  
  25.                 }  
  26.             }  
  27.             obj.value = FilteredChars;  
  28.             return false;  
  29.         } 

Summary

 
Although this article uses ASP.NET controls as an example, this JavaScript code fully supports standard HTML input controls as well.


Similar Articles