ASP.NET Web API      Interview Questions         HTML 5                               jQuery                              ASP.NET MVC framework

Thursday, February 28, 2013

JavaScript Validation for Letters and Numbers

During web development, almost always, we need to provide input validation on even simple web forms. And in case of web, JavaScript is the best option available for validating input on client-side. Server-side validation has its own important and it should be there but restricting user at very first step is always needed.

So, in this web development article, I am trying to present some requirement to limit the scope of the article, those are as follows:
  1. Only Numeric 
    Only numeric input should be allowed for some fields. So, user can’t enter non-numeric characters in those particular fields. One step further, user can’t even copy-paste non-numeric input.
  2. Only Character 
    Limited to alphabetic character input only with an exception i.e. space character that may require even if we are entering only alphabets.  Similarly, copy-paste must be restricted for other characters.
  3. Alphanumeric 
    Alphanumeric input allowed for certain fields but very restricted. A lot 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 following fields.
  • User Full Name -> Only alphabet character and space.
  • Username -> Only alphabet characters with dot (“.”) or dash(“-“).
  • 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.

Firstly, User Full Name field that will allow to enter only alphabets and space character. Alphabets can be capital or lower case characters. For Example, my son’s complete name will be  “Muhammad Ahmad”. So, following field will take input accordingly.

<asp:TextBox ID="txtFullName"
                onkeypress="return ValidateLettersWithSpaceOnly(event);"
                onPaste="return ValidateFullNamePaste(this);"
                MaxLength="50" runat="server">
</asp:TextBox>


JavaScript function validating input is:

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;
}

Secondly, Username/Login field will allow to enter alphabet, dot(“.”) or dash(“-“) characters.

<asp:TextBox ID="txtUsername" 
onkeypress="return ValidateUsernameOnly(event);"
              onPaste="return ValidateUsernamePaste(this);" 
MaxLength="30" runat="server">
</asp:TextBox> 

function ValidateUsernameOnly(evt) 
{
            evt = (evt) ? evt : event;
            var characterCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
          ((evt.which) ? evt.which : 0));
if (characterCode > 31 && (characterCode < 65 || characterCode > 90) && (characterCode < 45 || characterCode > 46) &&
(characterCode < 97 || characterCode > 122) && (characterCode < 48 || characterCode > 57)) {
                return false;
            }
            return true;
 }

function ValidateUsernamePaste(obj) 
{
            var totalCharacterCount = window.clipboardData.getData('Text');
            var strValidChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.";
            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;
  }

For Email field, a standard email validation is applied but it’s triggered on form submission.

<asp:TextBox ID="txtEmail" 
MaxLength="30" runat="server">
<asp:Button ID="btnSave" Text="Create User" runat="server" 
OnClientClick="validateEmail(this);" />

function validateEmail(emailField)
 {
            var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
            if (reg.test(emailField.value) == false) {
                alert('Invalid Email Address');
                return false;
            }
            return true;
        }

And finally, numeric validation for phone number field as follows.

<asp:TextBox ID="txtPhone" 
onkeypress="return ValidateNumberOnly(event);"
onPaste="return ValidateNumberPaste(this);" 
MaxLength="10" runat="server">
              </asp:TextBox>

function ValidateNumberOnly(evt)
 {
if ((evt.keyCode < 48 || evt.keyCode > 57)) 
{
       evt.returnValue = false;
}
}

function ValidateNumberPaste(obj) 
{
            var totalCharacterCount = window.clipboardData.getData('Text');
            var strValidChars = "0123456789";
          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;
        }

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



Be social and share with others via:



Related Web Development Tutorials:

By Imran Abdul Ghani
Software Developer (Senior)
United Arab Emirates
Imran Abdul Ghani is working as Software Developer(Senior) with extensive knowledge in Web development technologies especially C#, ASP.NET, MVC, WCF, Web API, ADO.NET Entity Framework, jQuery etc. He has several years of experience in designing/developing enterprise level applications. He is Microsoft Certified Solution Developer for .NET (MCSD.NET) since 2005. You can reach his blogging at www.webdevelopmenthelp.net & www.topwcftutorials.net.

2 comments:

  1. Hi to every single one, it’s truly a good for me to visit this web page, it includes helpful Information. Informative article, just what I was looking for.
    Florida Web Design

    ReplyDelete