Click here to Skip to main content
15,886,137 members
Articles / Web Development / ASP.NET

A Tiny JavaScript Framework for Common Validation Scenarios

Rate me:
Please Sign up or sign in to vote.
4.88/5 (14 votes)
22 Jun 2012CPOL5 min read 50.1K   907   36   5
This article describes some reusable JavaScript functions that can be used to create the input fields which accept some specific type of data. It also provides functions to validate the data.

Image 1 

Introduction 

This article describes some reusable JavaScript functions that can be used to create the input fields which accept some specific type of data. It also provides functions to validate the data based on whether they are required and/or to be checked against a regular expression.

Background 

There are several scenarios where we want to restrict some particular type of user input. Example could be, I have a text box for accepting user's name so it doesn't make much sense for the text-box to accept the numeric characters. Similarly, if I have a text box that is supposed to take numeric input, then why should I allow users to enter alphabets in it. There could be many scenarios where we might want to accept some particular characters only. All the above mentioned scenarios not exactly fall in the category of validation but having such input fields will definitely make the other client side validation tasks easy.

The second aspect is validating the input fields before submitting. The jQuery validation provides a very clean way of handling such validations but perhaps in some cases, that seems like an overkill. A lot of validations can be handled if I have a simple validation mechanism for checking the required fields and validation against a regular expression.

What I am showing here is a tiny JavaScript file that I have been using from quite some time. This file contains some functions that provide the functionality of achieving all the above mentioned validations easily. Perhaps it might seem little basic to most but this little framework could come in really handy.

Important Note: The client side validation is a first check that will ensure the data validity. It will work for most of the casual users. More sophisticated users with malicious intent can still bypass the JavaScript code. So it is always a good idea to keep the same set of validations on server side too to ensure that invalid data cannot pass through.

Using the Code

Before looking into the code, let us look at the various scenarios that we will handle:

  1. Ability to create an input field that takes only alphabets. we should be able to specify whether spaces are allowed or not.
  2. Ability to create an input field that takes only numbers. We should be able to specify whether decimal is allowed or not.
  3. Ability to create an input field that takes alphabets and numbers. we should be able to specify whether spaces and decimals are allowed or not.
  4. Ability to create an input field that takes characters specific to date. we should be able to specify the separator we will be using.
  5. Ability to create an input field that accepts characters present in a regular expression.
  6. Validate a required input field before post-back.
  7. Validate an input field against a regular expression before post-back.

Let us look at each one of them in detail. I will provide the JavaScript function first and then how to use that function. If any function needs special attention, I will mention that too.

Accepting Characters Present in Regular Expression

JavaScript
//Function to create textbox based on regular expressions
function AcceptRegExOnly(event, regex)  
{   
    var keyCode = event.which ? event.which : event.keyCode;
    
    var keyPressed = String.fromCharCode(keyCode);
    return regex.test(keyPressed);
}; 

How to use this function from aspx markup:

ASP.NET
<asp:TextBox ID="TextBox7" runat="server" onkeypress="return AcceptRegExOnly(event, /^[a-zA-Z@]$/);">
</asp:TextBox>

Accepting Alphabets Only

There are two functions for doing this. The first function is doing this using the keycode. The second function is doing this using regular expressions. Both the functions will do the same task but if due to some reason, the keycode does not give proper results, the one with the regular expression implementation can be used. Notice that both the implementations take a Boolean argument to specify whether spaces are allowed or not. 

JavaScript
//Function to create alphabetic text box only - using keycodes
function AcceptAlphabetsOnly(event, allowSpaces) 
{
    var keyCode = event.which ? event.which : event.keyCode;
    
    if (    (keyCode >= 97 && keyCode <= 122) ||        //lets allow for the small alphabets
            (keyCode >= 65 && keyCode <= 90)  ||        //Let us allow the capital letters too
            ((allowSpaces == true) && (keyCode == 32))  //allow space conditionally 
                                                        //based on the control's choice
       )
    {
        return true;
    }
    
    return false;
};

//Function to create alphabetic text box only - using regex
function AcceptAlphabetsOnlyEx(event, allowSpaces) 
{
    if(allowSpaces == true)
    {
        return AcceptRegExOnly(event, /^[a-zA-Z ]$/);
    }
    return AcceptRegExOnly(event, /^[a-zA-Z]$/);
};

And now, let us see how they can be used from the aspx markup.

ASP.NET
<asp:TextBox ID="TextBox1" runat="server" onkeypress="return AcceptAlphabetsOnly(event, false);">
</asp:TextBox>

<asp:TextBox ID="TextBox2" runat="server" onkeypress="return AcceptAlphabetsOnlyEx(event, false);">
</asp:TextBox>

Accepting Numeric Only

There are two functions for doing this. The first function is doing this using the keycode. The second function is doing this using regular expressions. Both the functions will do the same task but if due to some reason, the keycode does not give proper results, the one with the regular expression implementation can be used. Notice that both the implementations take a Boolean argument to specify whether decimal is allowed or not.

JavaScript
//Function to create numeric text box only - using keycodes
function AcceptNumericOnly(event, allowPeriod) 
{
    var keyCode = event.which ? event.which : event.keyCode;    
    
    if( (keyCode >= 48 && keyCode <= 57) ||         //lets allow only numerics 
        ((allowPeriod == true) && (keyCode == 46))  //allow period conditionally 
                                                    //based on the control's choice
      )
    {
        return true;
    }   
    
    return false;
};

//Function to create numeric text box only - using regex
function AcceptNumericOnlyEx(event, allowPeriod) 
{  
    if(allowPeriod == true)
    {
        return AcceptRegExOnly(event, /^[0-9.]$/);
    }
    return AcceptRegExOnly(event, /^[0-9]$/);
};

And now, let us see how they can be used from the aspx markup.

ASP.NET
<asp:TextBox ID="TextBox3" runat="server" onkeypress="return AcceptNumericOnly(event, false);">
</asp:TextBox>

<asp:TextBox ID="TextBox4" runat="server" onkeypress="return AcceptNumericOnlyEx(event, false);">
</asp:TextBox>

Accepting Alphabets and Numeric Only

There are two functions for doing this. The first function is doing this using the keycode. The second function is doing this using regular expressions. Both the functions will do the same task, but if due to some reason, the keycode does not give proper results, the one with the regular expression implementation can be used. Notice that both the implementations take two Boolean argument. The first one is to specify whether spaces are allowed or not and the second one to specify whether the decimal is allowed or not.

JavaScript
//Function to create alphanumeric text box - using keycodes
function AcceptAlphaNumericOnly(event, allowSpaces, allowPeriod)  
{
    if( (AcceptAlphabetsOnly(event, allowSpaces) == true) ||    //Create alphabetic text box
        (AcceptNumericOnly(event, allowPeriod) == true)         //Create numeric text box
      )
    {
        return true;
    }
    
    return false;
};

//Function to create alphanumeric text box - using regex
function AcceptAlphaNumericOnlyEx(event, allowSpaces, allowPeriod) 
{
    if(allowSpaces == true && allowPeriod == false)
    {
        return AcceptRegExOnly(event, /^[a-zA-Z0-9 ]$/);
    }
    if(allowPeriod == true && allowSpaces == false)
    {
        return AcceptRegExOnly(event, /^[a-zA-Z0-9.]$/);
    }
    if(allowPeriod == true && allowSpaces == true)
    {
       return AcceptRegExOnly(event, /^[a-zA-Z0-9 .]$/);
    }
    
    return AcceptRegExOnly(event, /^[a-zA-Z0-9]$/);
};

And now, let us see how they can be used from the aspx markup.

ASP.NET
<asp:TextBox ID="TextBox5" runat="server" 
 onkeypress="return AcceptAlphaNumericOnly(event, false, false);">
</asp:TextBox>

<asp:TextBox ID="TextBox6" runat="server" 
 onkeypress="return AcceptAlphaNumericOnlyEx(event, false, false);">
</asp:TextBox>

Accepting Date Specific Characters Only

JavaScript
//This function will create the date text box
function AcceptDateCharacters(event, separator)
{
    if(separator.length != 1)  //only pass single character separators here
    {
        return false;
    }
    //lets allow digits
    var expression = "^[0-9";
    
    //lets allow the separator character
    expression += separator;
    
    //lets complete the expression
    expression += "]$";
    
    var regex = new RegExp(expression);    
    return AcceptRegExOnly(event, regex)  
};

And now, let us see how this function can be used to accept date string using '-' as the separator.

ASP.NET
<asp:TextBox ID="TextBox8" runat="server" onkeypress='return AcceptDateCharacters(event, "-");'>
</asp:TextBox>

Setting Up the Validation Before Submitting the Form

Now before moving ahead, we will see the markup code for submit button as we will now be dealing with the client side validations before the submit to server will happen.

ASP.NET
<asp:Button ID="Button1" runat="server" Text="Submit" OnClientClick="return validateForm();" />

Checking Input Field for Required Field

Let us now see the function which will be called from before submit to ensure that the required field values are present or not.

JavaScript
//This function will check for the mandatory field
function CheckMandatoryInput(input)
{   
    if(input.value.length == 0)
    {   
        input.style.borderColor="Red";
        input.title = "This field is mandatory";
        return false;
    }
    
    input.style.borderColor="";
    input.title = "";
    return true;
};

And how it should be used from client side markup page.

JavaScript
function validateForm()
{
    if(CheckMandatoryInput(document.getElementById("TextBox1")) == false)
    { 
        return false;
    }            
}

Checking Input Field Against a Regular Expression

Let us now see the function which will be called from before submit to ensure that the value present in the input field is as per the required regular expression or not..

JavaScript
//This function will check for the input using regular expression
function CheckWithRegExp(input, regex, mandatory)
{
    if(mandatory == true && CheckMandatoryInput(input) == false)
    {
        return false;
    }
    if(regex.test(input.value) == false)  
    {
        input.style.borderColor="Red";
        input.title = "This is not a valid input";
        return false;
    }    
    
    input.style.borderColor="";
    input.title = "";
    return true;
};

And how it should be used from client side markup page.

JavaScript
function validateForm()
{ 
    if(CheckWithRegExp(document.getElementById("TextBox1"), /^[a-z]{3,10}$/, true) == false)
    {                
        return false;
    }
}

Now, we have successfully configured our input fields to accept the desired input and provided some very basic validation before submitting the form.

Points of Interest

This JavaScript is something I created to use for client side validation. The main idea of posting this as an article has spurred because of the questions asked in "Quick Questions" section of Codeproject. There seem to be many beginners struggling to get this kind of functionality and perhaps this reusable code can be helpful to them.

History

  • June 20, 2012 - First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India

I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.

  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]

  • Microsoft MVP 2015

Comments and Discussions

 
GeneralMy vote of 5 Pin
rgboss3-Apr-13 19:43
rgboss3-Apr-13 19:43 
GeneralGood one Pin
ss291019763-Jan-13 9:04
ss291019763-Jan-13 9:04 
GeneralMy vote of 5 Pin
member6020-Jun-12 7:46
member6020-Jun-12 7:46 
QuestionDecimal separator from numeric keyboard not working for me Pin
Selvin20-Jun-12 2:34
Selvin20-Jun-12 2:34 
AnswerRe: Decimal separator from numeric keyboard not working for me Pin
Rahul Rajat Singh20-Jun-12 2:38
professionalRahul Rajat Singh20-Jun-12 2:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.