Wednesday, 21 January 2009

Basic Validation using jQuery

I am a big fan of the jQuery Javascript Library and use it widely in most of my projects. It's light weight, simple and really powerful. The validations I have written will be using the jquery library to perform their tasks.

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.

Change

We all get used to our way of living and feel comfortable only when things happen in that particular way. Why???... Change is also a part of life. The sooner you get used to it the better you'll function...

Instead of being opposed to change, why not first take a moment to understand the underlying idea? We could ask the following questions:
  • Why did the change happen? or What triggered the change?
  • What are the advantages/disadvantages of this change?
  • If applicable, who will it affect and in what way?
If the answers to the above questions, turn out mostly negative, we can re-think the change.

As you may already know, change could be for the better or for the worse. Lets understand this with the help of some examples.

A Good Change:
Scenario: The Administration department in your organisation has decided that from now onward every computer in the organisation will have a black desktop background and every user will switch off their screens when not at their desk. You are used to having pictures of your as your desktop wallpaper, so, naturally you do not accept this very graciously.
Now, stop and ask yourself the above questions.

Q. Why did the change happen? or What triggered the change?
A. High energy consumption caused the organisation to review the energy usage. It was reported that a lot of energy was being wasted and that if employees switched off their computer screens when not at their desk and maintained black desktop wallpapers, energy consumption would be reduced by 20% leading to a 10% reduction in the organisation's expenses.

Q. What are the advantages and disadvantages?
A. Significant increase in company profits. Company passes this on to the employees in the form of bonus. The Company is more environment friendly.
The disadvantage, according to you may be that you will be staring at a blank, black desktop. But consider this, how often in a day and for how long do you look at your desktop?

Q. Who will it affect and in what way?
A. It will affect all the employees and the organisation as a whole. Employees will get better benefits. The organisation's profits will increase and energy will be saved.
You're still thinking about the blank, black desktop aren't you?

Most of the effects of the change in the above scenario are positive to a majority of the elements affected by the change. Therefore, we can safely conclude that the change is good.


A Bad Change
:
Scenario: You manage a team at work and have a manager above you. Your manager has a bad temper and yells at you for even small mistakes. Soon you pick up this habit and also develop a bad temper since you feel that you manager's way is very effective.
Again ask yourself the following questions:

Q.
Why did the change happen? or What triggered the change?
A. You felt your manager's way is effective and so you picked it up. Also, the anger and frustration created by him yelling at you all the time needs to be vented, and for that you knowingly/unknowingly choose those you interact with (your team, your family, etc.)

Q. What are the advantages and disadvantages?
A. You may be able to achieve your work on time most of the time. But this won't always happen. Also, the temper will cause stress for you and those you interact with. Your relationships with others will also be affected. Yelling at people for every single thing won't bring you close to them.

Q. Who will it affect and in what way?
A. All those you interact with like your family, team, etc. You will find yourself drifting apart from them.

Almost all the effects of this change are bad, not only for others but also for you. Therefore , this change becomes unnecessary and is bad.

When a change is bad you should see if the reasons for the change are important. If they are, then you should try to find alternatives. Perhaps, if you wish that your team meet targets more often, you can be more assertive and maybe employ a strategy like giving performance based incentives.

Don't instantly oppose/support change. Take some time, think about it and plan carefully.

Remember, Change is good, but only if it is
  • In the right direction.
  • To the right magnitude.
  • For the right reasons.