Our blog, keeping you up-to-date on our latest news.

 

Add Validation to Contact Form

December 17, 2010 at 1:21 pm | Blog | 2 comments

 

A PengbosInspiration theme user asked for validation on contact form, especially for the email field. It should be a very common request for developers using contact form. I made a little change to the javascript codes.

the original javascript code for submitting a contact form is as follow:

var theme_template_dir = jQuery("meta[name=theme_template_dir]").attr('content');
jQuery(document).ready(function(){
        jQuery('<div></div>')
        .insertBefore('#log')
            .attr('id','log_wait')
            .css('display','none')
            .addClass('ajax-loading')
            .ajaxStart(function(){jQuery(this).show();})
            .ajaxStop(function(){jQuery(this).hide();});
 
        jQuery('#contacts').submit(function() {
            jQuery.post(theme_template_dir + '/include/gmail_sendmail.php',jQuery(this).serialize(), function(data){
            jQuery('#log').empty();
            jQuery('<div></div>')
            .attr('id','log_res')
            .appendTo('#log')
            .html(data);
        });
        return false;
    });
});


It uses jQuery attribute query method to get the “theme_template_dir” value which is added in the “header.php”, if you look into the header.php file, there is a meta data like

 <meta name="theme_template_dir" content="<?php bloginfo('template_directory'); ?>" />

the next two code blocks are for submitting the contact form and displaying the result status.
the first code block is for showing the loading image when the form is submitted and hiding the loading image when the Ajax request is finished.
the second code block is for submitting the contact form with Ajax, and displaying the result data.

As you may see, there is no validation at all. We need to check user input when the user clicks submit button. So before submitting the form, we need to check each field one by one.

The logic and requirement is really simple

1. stop the form from being submitted with e.preventDefault();
2. check each field one by one
3. submit the form

so let’s exam the code:

var theme_template_dir = jQuery("meta[name=theme_template_dir]").attr('content');
jQuery(document).ready(function($){
        $('#send_message').click(function(e){
                //stop the form from being submitted
                e.preventDefault();
                /* declare the variables, var error is the variable that we use on the end
                to determine if there was an error or not */
                var error = false;
                var errorMsg = "";
 
                var name = $('#visitor').val();
                var email = $('#visitormail').val();
                var message = $('#notes').val();
                /* 
                The only difference from these checks is the email checking, we have
                email.indexOf('@') which checks if there is @ in the email input field.
                This javascript function will return -1 if no occurence have been found.*/
                if(name.length == 0){
                        error = true;
                        errorMsg = errorMsg + " name is empty";
                }
                if(email.length == 0 || email.indexOf('@') == '-1'){
                        error = true;
                        errorMsg = errorMsg + " email is not valid";
                }
                if(message.length == 0){
                        error = true;
                        errorMsg = errorMsg + " message is empty";
                }
                if(error){
                    $('#log').empty();
                    $('<div></div>')
                    .attr('id','log_res')
                    .appendTo('#log')
                    .html('<div class=\"error\">'+errorMsg+'</div>');
                }
                //now when the validation is done we check if the error variable is false (no errors)
                else{
                    $('#log').empty();
                    $('#log_wait').remove();
                    $('<div></div>')
                    .insertBefore('#log')
                        .attr('id','log_wait')
                        .css('display','none')
                        .addClass('ajax-loading')
                        .ajaxStart(function(){$(this).show();})
                        .ajaxStop(function(){$(this).hide();});
 
                    $.post(theme_template_dir + '/include/gmail_sendmail.php',$('#contacts').serialize(), function(data){
                        $('#log').empty();
                        $('<div></div>')
                        .attr('id','log_res')
                        .appendTo('#log')
                        .html(data);
                    });
 
                }
        });    
});

To use this code in the PengbosInspiration theme, just copy everything to the form-contact-validate.js.

<< Back to Blog Discuss this post

 

2 Comments to “Add Validation to Contact Form”

  1. Snake says:

    hey, your contact form is BR0KEN!!! seems like you have made validation a little bit too strict :)

    I just wanted to contact youu to tell you, that your aurelius download generates a 404 error!

    admin Reply:

    I am terribly sorry for the inconvenient.

    I have fixed the 404 error on aurelius download, now you can access it.

    i am using free hosting service from bytehost. Recently, they close all services on smtp protocol. So the contact form is not working anymore.

    I am considering switch to premium program from them. But as you know, i have not so much incomings from this website. So i will stick to the free hosting for a while, when i have enough budget, i will switch to premium service.

    Thanks for your valuable input. I really appreciate!