Friday, December 3, 2010

Form validation using jQuery

I have written a simple form validation script using jQuery for one of my projects though it have improvement opportunity. Anyone can use it easily by following four simple steps below:

STEP 1: Add jQuery plugin to your application

STEP 2: Copy following codes in to a JavaScript file and add the file after jQuery plugin
var Form = {
    errors:0,
    validation_class:'.validate-form', //Form class name to validate
    novalidate_class:'.no-validate-form', //Class name to ignore validation
    invalid_class:'invalid', //Class name to highlight invalid input
    required_class:'required', //Class name to validate required field

    //Use hash keys below as a class name to validate
    regex_to_validate:{
        'validate-password':/^[A-Za-z0-9!@#$%^&*()_]{6,20}$/,
        'validate-numeric':/^(\d|-)?(\d|,)*\.?\d*$/,
        'validate-username':/^[A-Za-z0-9_]{5,20}$/,
        'validate-email':/^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/
    },

    message_id:'#validation_message',
    error_message:'Please fix missing or erroneous entries marked with red borders.',

    addError:function (item) {
        item.addClass(Form.invalid_class).css("border", "1px solid red");
    },

    removeError:function (item) {
        item.removeClass(Form.invalid_class).css('border', '');
    },

    flashMessage:function () {
        if (Form.errors) {
            if ($(Form.message_id).length) {
                $(Form.message_id).html(Form.error_message)
                    .css('display', 'block')
                    .css('font-size', '10px')
                    .css('color', 'red')
                    .css('padding', '5px 0');
            } else {
                alert(Form.error_message);
            }
        }
    },

    classNames:function () {
        var class_names = '.' + Form.required_class;

        $.each(Form.regex_to_validate, function (key, value) {
            class_names += (class_names == '' ? '' : ', ');
            class_names += '.' + key;
        });

        return class_names;
    },

    replaceItemText:function (item) {
        var val = item.val();

        item.focusin(function () {
            if (/^(Title|First\sName|Last\sName)/.test($(this).val())) {
                $(this).val('');
            }
        });

        item.focusout(function () {
            if ($(this).val() == '') {
                $(this).val(val);
            }
        });
    },

    runtimeValidation:function () {
        var class_name;

        $(Form.validation_class).find(Form.classNames()).each(function () {
            class_name = $(this).attr('class').toString();

            if (class_name.indexOf('replace-text') != -1) {
                Form.replaceItemText($(this));
            }

            $(this).focusout(function () {
                Form.validItem($(this));
            });
        });
    },

    validItem:function (item) {
        var error = false;
        var class_name = item.attr('class').toString();

        if (class_name.indexOf(Form.required_class) != -1 && item.val().toString() == '') {
            Form.addError(item);
            error = true;
        } else {
            $.each(Form.regex_to_validate, function (key, value) {
                if (class_name.indexOf(key) != -1 && !value.test(item.val())) {
                    Form.addError(item);
                    error = true;
                    return;
                }
            });
        }

        if (!error)
            Form.removeError(item);

        return !error;
    },

    validateItems:function () {
        Form.errors = 0;

        $(Form.validation_class).find(Form.classNames()).each(function () {
            Form.errors += (Form.validItem($(this)) ? 0 : 1);
        });

        Form.flashMessage();
    }
};

$(document).ready(function () {
    Form.runtimeValidation();

    $(Form.validation_class).submit(function () {
        Form.validateItems();
        return !Form.errors
    });

    $(Form.novalidate_class).submit(function () {
        return true;
    });
});

STEP 3: Customize form validation settings like class names and message as you want

STEP 4: Put the class names in to your form to validate

That's all. Now just click in to the submit button and see the magic...

View Demo



Friday, November 19, 2010

PHPMailer: Called Mail() without being connected

I was getting the error message to send email using PHPMailer but didn't get so much help after googling. Then, started to debug the error source and found that it generate for SMTP port and protocol mismatch.

Usually, SMTP port is not same for different protocol with/without ssl. So, It's very important to find the correct SMTP port and protocol.

Tuesday, October 12, 2010

Mysql backup on linux using ssh and cron

Sometimes, we may need to backup and synchronize mysql on linux as a background process. Linux has a great program for this called cron. It allows tasks to be automatically run in the background at regular intervals.

Create a script file(.sh) using following code snippet to backup and restore database in to another database:
ssh user@remote-host "mysqldump -u my-remote-db-username --password=my-remote-db-password my-remote-db-name" | mysql -udb-username --password=db-password --host=host-name -C db-name


Open a terminal and run:
sudo crontab -l

To edit the list of cronjobs you can run following code which will open default editor to let us the crontab:
sudo crontab -e

You can configure your script in to crontab by following code:
* * * * * /bin/execute/this/script.sh


The above five stars represent different date parts in the following order:
  1. minute (from 0 to 59)
  2. hour (from 0 to 23)
  3. day of month (from 1 to 31)
  4. month (from 1 to 12)
  5. day of week (from 0 to 6) (0=Sunday)

Friday, July 9, 2010

Find mouse pointer position using JavaScript

Sometimes we need to know the mouse cursor position to perform a certain action at that place.

For example, I need to show up a popup div near the mouse cursor position when user click over a particular field/link. You can get the mouse cursor position using following codes:

function getCursorPosition(e) {
    e = e || window.event;

    var pos = {x:0, y:0};

    if (e.pageX || e.pageY) {
        pos.x = e.pageX;
        pos.y = e.pageY;
    } else {
        var de = document.documentElement;
        var b = document.body;
        pos.x = e.clientX + (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        pos.y = e.clientY + (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }

    return pos;
}

Tuesday, June 22, 2010

How to do custom redirection of a website

Usually the redirection needs when a website changed/move to different location though it may use for lots of other purposes. In this post, I have explain how you can do it by using .htaccess

Say, your site has lots of URL and you want to redirect some of those which query string has a parameter name “option” and the value is “redirect”.

Below are the codes to redirect into new URL:
RewriteEngine on
RewriteCond %{QUERY_STRING} option=redirect
RewriteRule (.*) http://newsite.com/index.php?%{QUERY_STRING} [R=301,L]

Just copy above lines into .htaccess file and place it to root directory in your application.

Some helpful posts:

Sunday, June 20, 2010

Change file extension in URL

In my previous article I have shown how you can use different extension of a file instead of .php explicitly but in this post I have explain how to rewrite the URL instead of renaming the file extension explicitly.

To rewrite the URL you must add following lines in a .htaccess file and place it to root directory of your application.
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)\.htm$ $1.php [nc]

The above code will rewrite the product.php to product.html.

And following is the code to pass parameters with URL
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)\.html(.*)$ $1.php$2

Some related posts:

Hide the fact that the web pages are written in PHP

Sometimes you may want to hide the fact of your web site’s written language to visitors then you can do it easily by using .htaccess Say, you have developed your site by using PHP and wanted to show it as ASP then you can do it by using following tricks:

Just add following line in the .htaccess file and place it to application root directory.
AddType application/x-httpd-php .asp
Now everyone have to use all files of the application by using .asp though the application was written in PHP.

Friday, May 7, 2010

HTML coding guidelines

This is my third article about coding guidelines. In this article I wanted to give you some general guidelines for HTML coding that will help to improve readability, maintainability and code reuse. It will reduce browser related problem. Following are some guidelines:
  • Must be use doctype in your web page.
  • Everyone should be write well-formed HTML code.
  • Indent HTML code constantly
  • Use small letter constantly. It will increase readability.
  • ID should be unique in a page and pick a meaningful name for this. Should be follow a standard constantly. Can use underscore (_) to separate meaningful words.
  • Name tag can follow a same standard like ID. It will be easier to read.
  • Should be use ID for dynamic element.
  • Avoid inline CSS. Use separate file for CSS stylesheet.
  • Avoid longer line. Break the line when a statement will not fit on a single line.
  • Use commenting as less as possible but use sensibly.
  • All nested attributes must be properly nested.
  • Attributes must be quoted.
  • Validate HTML code using W3C validation service at - http://validator.w3.org

Some related posts:

Friday, April 16, 2010

Specify rendering engine of IE

Internet Explorer 8 supports different document compatibility to ensure that your web pages have a consistent appearance in future versions.

If you are having trouble on a site in different IE, you can use specific rendering mode to display your web pages by using simple META tag. Below is the META tag to use IE7 rending in IE8:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
Details of defining rendering engine in IE

Sunday, March 21, 2010

The bundled mysql.rb driver has been removed from Rails 2.2

After two months, I have started working on rails again and upgraded Rails to 2.3.2 on my laptop. After upgraded when I have tried to run a sample rails application and got following errors:
=> Booting WEBrick
=> Rails 2.3.2 application starting on http://0.0.0.0:3000
!!! The bundled mysql.rb driver has been removed from Rails 2.2. Please install the mysql gem and try again: gem install mysql.
=> Call with -d to detach
[2010-03-21 04:39:09] INFO  WEBrick 1.3.1
[2010-03-21 04:39:09] INFO  ruby 1.8.6 (2007-09-24) [i386-mswin32]
[2010-03-21 04:39:09] INFO  WEBrick::HTTPServer#start: pid=5032 port=3000
=> Ctrl-C to shutdown server
After getting the above error I have installed newer version of mysql gem but problem was not solved. Then just copy the MySQL dll from mysql/bin/libmysql.dll to ruby/bin/libmysql.dll. And it worked perfectly.

Friday, February 5, 2010

JavaScript coding standards/conventions

The long-term value of software is depended of the quality of codebase and it helps to reducing the weakness of programs. That’s why we should follow standards while writing Js code which will increase the code quality. I am trying here to give you some idea/suggestion to write better Js code.

Below are some suggestions which should follow everyone:

  • Try to avoid embedded JavaScript code in HTML files. It will decrease page loading time and increase caching and compression opportunity.
  • Avoid longer line. Break the line when a statement will not fit on a single line.
  • All JavaScript programs should be stored in a separate Js file and should be placed as late in the body as possible. This reduces the effects of delays.
  • Indenting should be followed constantly. Now a day’s space is not a matter because you can eliminate by using minification.
  • Function name should start with small letter and all meaningful word should be capital letter.
  • Should not use space between the name of a function and left parenthesis and separate parameters by a space.
    function showFlashMessage(message, message_type){
    
    }
  • Global variable should be all caps, local Variable in small letter and all meaningful word should be separate by underscore (_)
  • All variables should be declared before using though JavaScript does not require this. The variable declaration statement should be the first statement of a function. It will make your code easier to read.
  • Must be use semicolon (;) at the end of the every statement and each line should contain only a statement.
  • Use left curly braces in the same line of the function or a statement and a line break for curly braces.
    for(){
    if(condition){
     statements;
    }
    }
  • Try to avoid comma operator except for disciplined use.

Some related posts:
I strongly recommend to read 24 JavaScript Best Practices for Beginners

Sunday, January 3, 2010

CSS coding guidelines/conventions

While writing CSS code, everyone should be follow a standard or convention. It is not important to remember a convention what should be follow. Important is to follow any style constantly, actually it is a common sense though it is not common sense to everybody. I am just writing it to provide others with one point of view and a starting point of their own style sheet coding standards.

Below are some ideas for writing CSS code:
  • Must be placed CSS code in a separate file as much as possible instead of in-line CSS.
  • Give the descriptive and meaningful name of CSS files
  • Use class instead of ID as CSS identifier. IDs to be used if there is only one instance of that element on a page and classes must be use to style several elements in the same way.
  • Write meaningful class name instead of short one and use a dash (-) as a separator of a CSS class name.
  • Always use lowercase while writing a CSS class name Otherwise it may occur browser problems.
  • Add opening curly bracket on the same line as the selector identifier.
  • Should write a common design for Input, Button, form and other html elements for whole application at the top of the stylesheet
  • Group the rules for same type of elements and its pseudo-elements together.
  • Use spacing while describing attribute of a class to improve readability.
  • Can use empty line between different CSS class to improve readability.
  • For visual emphasis use space to separate property and value.
  • Try to use shorthand property instead of long property because it will increase readability. Use background-color, background-position, background-image, and background-repeat etc. instead of background
  • Use em instead of pix for sizing, line heights etc to allow visitors to use the built-in browser text sizing. See the CSS Techniques for Web Content Accessibility Guidelines 1.0 for more details.
  • Must be use semicolon at the end of the line/statement.
  • Try to avoid presentation specific words as identifier, like black, green etc.

There are lots of benefits to follow a standard some of those are given below:
  • It makes your code more predictable and understandable.
  • Anyone can change/debug and pick a design easily.
  • Reduce time for design/development, update and maintenance
  • Increased accessibility
  • Adhere to W3C recommendations, improving interoperability and ensuring
    greater longevity etc.

I am just trying to give you some ideas and inspire to adopt a CSS coding standard. Hopefully it will be very helpful to all of you.


Some related posts: