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.
-
Ability to create an input field that takes only alphabets. we should be able to specify
whether spaces are allowed or not.
-
Ability to create an input field that takes only number. we should be able to specify
whether decimal is allowed or not.
-
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.
-
Ability to create an input field that takes characters specific to date. we should be able to specify the separator we will be using.
-
Ability to create an input field that accepts characters present in a regular expression.
- Validate a required input field before post-back.
- 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 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 AcceptAlphabetsOnly(event, allowSpaces)
{
var keyCode = event.which ? event.which : event.keyCode;
if ( (keyCode >= 97 && keyCode <= 122) || (keyCode >= 65 && keyCode <= 90) || ((allowSpaces == true) && (keyCode == 32)) )
{
return true;
}
return false;
};
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 AcceptNumericOnly(event, allowPeriod)
{
var keyCode = event.which ? event.which : event.keyCode;
if( (keyCode >= 48 && keyCode <= 57) || ((allowPeriod == true) && (keyCode == 46)) )
{
return true;
}
return false;
};
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 AcceptAlphaNumericOnly(event, allowSpaces, allowPeriod)
{
if( (AcceptAlphabetsOnly(event, allowSpaces) == true) || (AcceptNumericOnly(event, allowPeriod) == true) )
{
return true;
}
return false;
};
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
function AcceptDateCharacters(event, separator)
{
if(separator.length != 1) {
return false;
}
var expression = "^[0-9";
expression += separator;
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.
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..
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