Tuesday 25 Nov 2008

Javascript comments check

WordpressBy default in blogs, when we post an invalid comment (missing field, invalid e-mail...) we arrive on a error page. Unfortunately this method has the following disadvantages:

  • te be often a standard blog page, white, without your theme,
  • to require a new page download,
  • then visitors must go back to correct the comment.

In this article, I will show how to verify the comment fields on your blog instantly with Javascript by showing a error dialog box if something is missing. :-)

Javascript for comments

This add-on requires to modify the files of your theme, but relax if you're not familiar with HTML and PHP, it's very easy.

At least if you have a WordPress blog because I will explain for it. ;-) The modification is of course useless if you already have a plugin like AjaxComments which modify the default comments.


Stage 1: the Javascript file

First, you must create a Javascript file. Here is a basic verification file.

You must save it in the directory /wp-content/plugins/ (this is of course adaptable if you can do it).


I choose to separate each error message, and I consider that only the name and comment are required, the e-mail and URL are facultative. If you have plugins adding fields, you can also check them, but it's up to you to adapt to your plugins. ;-)

Stage 2: inclusion in the theme

Now this file must be used in your theme. Go in /wp-content/themes/ then in your theme folder, edit the file header.php to add just before </head>

<script type="text/javascript" src="/wp-content/plugins/comments.js"></script>


Then in comments.php, there should be only one <form> element. Search a line close to:

<form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php" method="post" id="commentform">

Add at the end of this line, just before the ending >, this:

onsubmit="javascript:return com(this)"


You only need to send on your site these 2 modified files and the comments.js file. I do this update on this site, so you can test below that validate show an error message if some field are empty. :-)

Related tutorials:

cafĂ© Did this article help you? 
Buy me a coffee!

3 answers at “Javascript comments check”

  1. 1
    hkjh said:


  2. 2
    David (azure-dev.kizone.net) said:

    This is a test? :D

  3. 3
    Serg (kzsoft.ru) said:

    Your site looks cool

Leave a comment (all comments are moderated, don't waste time with spam)

Azure Dev