Using jQuery to Validate the Standard WordPress Comment Form

WordPress does not natively validate its comment submission form, but it can be instructed to do so by developing a custom plugin which makes use of the popular Bassistance jQuery library. This library is specifically designed to validate forms and print any relevant errors before submission, and it’s by far the most widely-used way among web designers and developers to validate forms without requiring a great deal of extra coding or programming.

That library, in combination with the existing WordPress comment form, some minor PHP modifications, and a well-crafted stylesheet, is the key to bringing user interactivity into the 21st century. Here’s how it’s done using WordPress:

First, Get the Proper jQuery Libraries and Include Them in the Site Header

The first step to validating the standard WordPress comment form is securing the proper jQuery libraries to get the job done. This means obtaining the aforementioned Bassistance.de form validation plugin. From there, it will need to be uploaded to the server and placed within the plugin directory.

The second step is using the included WordPress variables for jQuery scripts in order to call the standard jQuery library and functions. This is done using a regular PHP tag like those used within entries, pages, categories, and other sections of the site. The tag is placed within the <head> tags in the current theme’s header.php file and it looks like this:

<?php wp_enqueue_script(jquery-ui-core); ?>

This is the only modification that needs to be made to the website’s header. The actually Basisstance.de jQuery library file will be included into the header by specifying it as a function within the plugin file itself. This ensures that the line of code will only be added to the website’s header when needed, especially because it’s a “niche” jQuery library rather than the core file which enables most of the jQuery functions themselves. When the header.php file has been successfully modified, saved, and uploaded, it’s time to move on and craft the plugin’s file structure and directories.

Specifying the CSS, Library, and Plugin File Directory Structure

This plugin is a bit more complex in file structure than the simple php-file-only method which is used for many more basic WordPress functionality enhancements. Instead of just a single file, this validation plugin will come with its own JavaScript library (Bassistance.de) and a stylesheet file which will dictate the actual appearance of validation errors and successes. Therefore, the following file structure should be created:

  • comment-validation
  • styling
  • stylesheet.css
  • libraries
  • comment-validation.php

Both the comment-validation.php file and the stylesheet.css file will need to be created from blank text files on the local computer or using an FTP client’s built-in text editing application. These will be uploaded to the server and then modified directly, rather than having both local and remote versions. This convergence keeps things synced up and makes sure that no changes are lost by accidentally overwriting either version of the file.

Be sure to place the jQuery library into the “libraries” folder and then upload all of the files directly to the server. For those who are unsure where a plugin folder should be uploaded, a quick reminder of the plugin directory’s location:

/home/public_html/wp-content/plugins/

When the uploading process has completed and the files are all uploaded, it’s time to start building functions into the actual plugin PHP file.

Identify the Plugin Using the Standard WordPress Header Information

Just like the stylesheet file included with every theme, WordPress requires that plugin files have a few basic pieces of information located at the top of the file before any functions are performed. This information identifies the plugin and allows it to be seen, activated, deactivated, or deleted, within the WordPress Dashboard. Here’s the information that needs to bet filled out:

/*
* Plugin Name: Comment Validation Using jQuery
* Plugin URI: http://www.your-site.com
* Description: Using the Bassistance.de jQuery form validation library, this plugin provides instant feedback on the validity and completion of a standard web form within the WordPress comments page.
* Version: 1.0
* Author: Your Name Goes Here
* Author URI: http://www.your-site.com
* License: GPL
*/

Remember to include the opening and closing comment tags before this heading so as not to encounter any PHP errors on the production website where this plugin will be used. After this information has been entered, save the file to the server and navigate to the plugin management page of the WordPress Dashboard. Scroll through the list of currently-uploaded plugins until “Comment Validation Using jQuery” appears in the list. This is simply to ensure that the heading information is complete and the plugin is appearing as it should be. Do not activate the plugin at this time.

Printing and Activating the Relevant jQuery Libraries

With all of the files uploaded, and the plugin having been clearly identified and available for activation, it’s now time to tell WordPress to initialize the jQuery libraries and put them into good use. This is done using a series of functions that first load the scripts on the page (in the header, where the jQuery Core UI script was added earlier) and then actually executing those scripts so that their functions become available to the comment form. Here’s how those functions appear when added to the plugin file.

function get_our_scripts() {
if(is_single() ) {
wp_enqueue_script(
'bassistance',
plugin_dir_url( __FILE__ ) . '/libraries/bassistance.js',
array('jquery'),
'1.8.1',
true
);

get_our_stylesheet(
'bassistance',
plugin_dir_url( __FILE__ ) . '/styling/stylesheet.css',
array(),
'1.0'
);}}

add_action('get_our_scripts');


function run_our_script() { ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#validation-message').validate({

Above, the script has been added to the page and activated via the run_our_script PHP function. What will now ensue is the addition of actual instructions so that the script knows how to tell when a form is valid or invalid, and when an error message should be displayed. The script will also be told which error message to display based on a form’s name and desired content. This is done by adding the following lines of code into the existing run_our_script function:

rules: {
author: {
required: true,
minlength: 5
},
email: {
required: true,
email: true
},
comment: {
required: true,
minlength: 140
}
},

messages: {
author: "You haven't entered a valid name. Try again!",
email: "Your email seems to be invalid. Please double-check for errors.",
comment: "Our website requires that your comment be at least 140 characters in length (the length of a standard tweet). Please speak up!"
}
});
);</script >
<?php }
add_action('get_our_script');
?>

Each of the rules above pertains exactly to the name of the standard comment form element which is being validated. So, too, do the labels of the error messages. They’ll be printed right alongside the identified form element should the need arise. After both the required form information and the pertinent error messages have been set, the function is closed and the PHP file is done being modified. It can now be uploaded to the server and activated within the WordPress Dashboard plugin management screen.

Add Content to the Stylesheet to Provide the Finishing Touches

Every error message defined within the PHP file is printed onto the page within its own <div> tag with a class of error. That means these error messages can be easily styled using either the theme’s stylesheet or the one included with the plugin. For continuity of style across themes, it’s best to style a plugin-specific feature with a plugin-specific stylesheet, and that’s the approach taken here. Navigate to the “styling” folder and, in the stylesheet.css folder, add the following class:

label.error {
YOUR STYLING INFORMATION GOES HERE;
}

It’s entirely up to you how the error message appears, but remember that a <div> tag is a block element. This means that borders, padding, margins, font and text styles, and a large number of other preferences can be defined without messing up the existing comment form. In fact, not a single change is required to the existing WordPress comment form or the site’s currently-in-use comment.php template for this plugin to do its job and look good in the process.

When the styling information has been completed, it’s time to save and upload the stylesheet file and navigate to a single entry page. Go ahead and enter some blatantly invalid information into the comment form and make sure that the right error appears when it should be doing so. Make sure that the defined style looks as good as anticipated and then, finally, take a break and enjoy the finished product.

Author: (40 Posts)

Vladislav Davidzon is the principal of US-based online marketing consultancy Vladislav Davidzon & Associates, developing integrative solutions through high impact search engine optimized WordPress websites for socially responsible customers of all sizes around the world.

Comments