Click here to Skip to main content
Click here to Skip to main content
Go to top

A Tiny Javascript Framework for Common Validation Scenarios.

, 22 Jun 2012
Rate this:
Please Sign up or sign in to vote.
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.

 

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 makes 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 provides 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 user 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 number. 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 decimal 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 a input field against a regular expression before post-back.

Let us look at each one of them in details. I will provide the javascript function first and then how to use that function. If any fucntion need special atention I will mention that too.

Accepting Characters present in Regular expression

//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: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 the regular expressions. Both the functions will do the same task but if due to some reasons 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. 

//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: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 the regular expressions. Both the functions will do the same task but if due to some reasons 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.

//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: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 the regular expressions. Both the functions will do the same task but if due to some reasons 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 second one to specify whether the decimal is allowed or not.

//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: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

//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: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: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 present or not.

//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.

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..

//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.

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

Now we have successfully configured out 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" sections of Codeproject. There seems 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)

Share

About the Author

Rahul Rajat Singh
Software Developer (Senior)
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[^]
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
GeneralMy vote of 5 Pinmemberrgboss3-Apr-13 19:43 
GeneralGood one Pinmembersankasuresh3-Jan-13 9:04 
GeneralMy vote of 5 Pinmembermember6020-Jun-12 7:46 
QuestionDecimal separator from numeric keyboard not working for me PinmemberSelvin20-Jun-12 2:34 
AnswerRe: Decimal separator from numeric keyboard not working for me PinmemberRahul Rajat Singh20-Jun-12 2:38 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140926.1 | Last Updated 23 Jun 2012
Article Copyright 2012 by Rahul Rajat Singh
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid