Purpose: My main objective here is to provide a validation class with the basic elements of form validation like blank, email, numeric, alpha-numeric and length validations.
If you desire simplicity and are ready to integrate the jQuery library into your system then read on...
Firstly you will need jQuery. To download jQuery visit: http://www.jquery.com/
Assuming that you have already downloaded jQuery, lets proceed.
You will need the validation object:
/*
* Javascript Validation Library
*
* This file is contains functions for javascript validation.
*
* @author Gavin Fonseca
* @created November 26, 2008.
*
*/
/*
* The Validation class object
*
* @params
* @return
*
*/
function Validations(){
this.ontest = false; // Deprecated -- true=> Test mode ON; false=> Test mode OFF
// Parameters for functions
this.param1 = '';
this.param2 = '';
// Function Declarations
this.setParams = setParams;
this.trim = trim;
this.isNotNull = isNotNull;
this.isValidEmail = isValidEmail;
this.isNumeric = isNumeric;
this.chkLength = chkLength;
this.isAlphaNum = isAlphaNum;
//******************************************
// BEGIN - Function Definitions
//******************************************
/*
* setParams(object): Function for setting the parameters for functions.
*
* @params Object with attributes containing values to be set
* @return Void
*
*/
function setParams(o){
if(typeof(o.par_1) != 'undefined'){
this.param1 = o.par_1;
}
if(typeof(o.par_2) != 'undefined'){
this.param2 = o.par_2;
}
} // function setParams(o)
/*
* trim(object): Function for trimming strings. The first two attributes of the object are considered (viz: o.par_1 & o.par2). "par_1" is required and must contain the string to be trimmed. A notification will show - when on test mode - if par_1 is missing. "par_2" is optional and contains the flag (i.e. "ltrim", "rtrim"). If par_2 is not ltrim or rtrim then the string is trimmed on both sides.
*
* @params Object with attributes containing values required for the function
* @return String (The trimmed string).
*
*/
function trim(o){
this.setParams(o);
if(this.param2 == "ltrim"){
return this.param1.replace(/^\s+/,"");
}
else if(this.param2 == "rtrim"){
return this.param1.replace(/\s+$/,"");
}
else{
return this.param1.replace(/^\s+|\s+$/g,"");
}
} // function trim(o)
/*
* isNotNull(object): Function for checking whether a string is NULL or EMPTY. Only the first attribute of the object is considered. This attribute must be the value to be validated.
*
* @params Object with one attribute containing value to be validated.
* @return Boolean (FALSE if String is NULL or EMPTY & TRUE if string has at least one character).
*
*/
function isNotNull(o){
this.setParams(o);
if(this.param1 == ''){
return false;
}
else{
return true;
}
} // function isNotNull(o)
/*
* isValidEmail(object): Function for checking whether a string is NULL or EMPTY. Only the first attribute of the object is considered. This attribute must be the value to be validated.
*
* @params Object with one attribute containing value to be validated.
* @return Boolean (FALSE if String is NULL or EMPTY & TRUE if string has at least one character).
*
*/
function isValidEmail(o){
this.setParams(o);
var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
//var re = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
if ( (this.param1 != '') && (!this.param1.match(re)) ){
return false;
}
else{
return true;
}
} // function isValidEmail(o)
/*
* isNumeric(object): Function for checking whether a value is numeric.
*
* @params Object with one attribute containing value to be validated.
* @return Boolean (FALSE if value is not numeric & TRUE if value is numeric.
*
*/
function isNumeric(o){
this.setParams(o);
if (isNaN(this.param1)){
return false;
}
else{
return true;
}
} // function isNumeric(o)
/*
* chkLength(object): Function for checking whether a value exceeds a maximum.
*
* @params Object with one attribute containing value to be validated.
* @return Boolean (FALSE if value exceeds length specified & TRUE if value doesn't exceed length specified.
*
*/
function chkLength(o){
this.setParams(o);
if (parseInt(this.param1.length) > parseInt(this.param2)){
return false;
}
else{
return true;
}
} // function chkLength(o)
/*
* isAlphaNum(object): Function for checking whether a value is alpha-numeric. First parameter is the value to be validated. Second parameter is optional and represents the type of alpha-numeric validation to be applied. Default is a username type of validation as explained below. In case you need to add an extra definition/type you can specify it in the function
*
* @params Object with two attributes.
* @return Boolean (FALSE if value is not alpha-numeric & TRUE if value is alpha-numeric.
*
*/
function isAlphaNum(o){
this.setParams(o);
var regEx = '';
if (this.param2 == 1){
// allow only letters, numbers, full stop (.) and underscores. should start with alphabet & end with alp. or num.
regEx = /^[A-Za-z]+(\w|\.+)([A-Za-z]|[0-9]+)$/;
}
else{
// allow only letters, numbers, and underscores. should start with alphabet & end with alp. or num.
regEx = /^[A-Za-z]+(\w+)([A-Za-z]|[0-9]+)$/;
}
if(this.param1.search(regEx) == -1){
return false;
}
else{
return true;
}
} // function isAlphaNum(o)
//******************************************
// END - Function Definitions
//******************************************
} // function Validations()
The object (function) above will handle all the validations.
Now you need to make the calls to the validation object's functions. Also these must be linked to your form. The function below will do that.
/*
* validate(): Function for validating the form. Uses above Validation object.
*
* @params
* @return Boolean (FALSE if validation fails & TRUE if validation passes.
*
*/
function validate(){
var objVal = new Validations();
var o = new Object();
var msg = '';
var fieldNames = '';
// Begin Validation for blank fields
$('.val_blank').each(function(){
o.par_1 = $(this).val();
o.par_1 = objVal.trim(o);
if(!objVal.isNotNull(o)){
fieldNames += '\n-\t' + $("label[for='"+$(this).attr('id')+"']").html();
}
});
if(fieldNames != ''){
msg += 'The following field(s) cannot be left blank:' + fieldNames + '\n\n';
fieldNames = '';
}
// End Validation for blank fields
// Begin Validation for email fields
$('.val_email').each(function(){
o.par_1 = $(this).val();
if(!objVal.isValidEmail(o)){
fieldNames += '\n-\t' + $("label[for='"+$(this).attr('id')+"']").html();
}
});
if(fieldNames != ''){
msg += 'Invalid email address(es) entered in:' + fieldNames + '\n\n';
fieldNames = '';
}
// End Validation for email fields
// Begin Validation for numeric fields
$('.val_num').each(function(){
o.par_1 = $(this).val();
if(!objVal.isNumeric(o)){
fieldNames += '\n-\t' + $("label[for='"+$(this).attr('id')+"']").html();
}
});
if(fieldNames != ''){
msg += 'The following field(s) must be numeric:' + fieldNames + '\n\n';
fieldNames = '';
}
// End Validation for numeric fields
// Begin Validation for fields with max. length value
$('.val_length').each(function(){
o.par_1 = $(this).val();
o.par_2 = $(this).attr('mlength'); // Get the value of the mlength attribute.
if(!objVal.chkLength(o)){
fieldNames += '\n-\t' + $("label[for='"+$(this).attr('id')+"']").html()+': '+o.par_2+' characters max.';
}
});
if(fieldNames != ''){
msg += 'Maximum length exceeded for the following field(s):' + fieldNames + '\n\n';
fieldNames = '';
}
// End Validation for fields with max. length value
// Begin Validation for alphanum fields
$('.val_alphanum').each(function(){
o.par_1 = $(this).val();
o.par_2 = $(this).attr('valtype'); // Get the value of the mlength attribute.
if(!objVal.isAlphaNum(o)){
fieldNames += '\n-\t' + $("label[for='"+$(this).attr('id')+"']").html()+': '+o.par_2+' characters max.';
}
});
if(fieldNames != ''){
msg += 'Maximum length exceeded for the following field(s):' + fieldNames + '\n\n';
fieldNames = '';
}
// End Validation for alphanum fields
if(msg != ''){
alert('Please Note:\n\n' + msg);
return false;
}
else{
return true;
}
} // function validate()
Keep the validation object and the validate function in the same file. You can keep it separate too, that's okay, but not requred, and if you do you will be making one extra call to download a file from your HTML page.
Well thats the entire structure. Remember, you can add your own functios to the validations object, but make sure you declare them at the top of that function. Also, include them in the validate function.
Now we need to link the validate function to validate the form. You can include this in your HTML page or in one of the javascript files for a particular page.
// Usage of jQuery to set the validation on the form.
$(document).ready(function(){
$('form').submit(function(){
return validate();
});
});
Surprised!!! Well... it's true that is all the code you need to get your form validation working.
Your HTML code should look like that at http://docs.google.com/Doc?id=df939p4f_3gzqm6hfz
Be sure to change the src tag value of the included script files.
You must be wondering what the classes (eg: class="val_blank val_length") for the HTML elements mean...
Well they are there primarily to help our validate function decide what validation to apply to which object. I have chosen class attribute values to help identify the type of validation since they are basic and every HTML element has a class attribute.
So how is the linking done?
$('.val_blank'): This is a jQuery selector. For more information on jQuery selectors visit http://docs.jquery.com/Selectors
Below is a list of classes and the validations that can be applied using them:
- val_blank: Checks if the element value is blank.
- val_email: Checks if the element value is a valid email addresses.
- val_num: Checks if the element value is entirely numeric.
- val_alphanum: Checks if the element value is alpha-numeric.
- val_length: Checks if an elements value exceeds a specified length. You will need to specify the maximum length by adding the mlength attribute to the element. Eg: mlength="100" means that the element value must not exceed 100 characters.
Please pardon any spelling mistakes in the documentation. I will be reviewing it later to make it more clear.