7 days of WordPress plugins, themes & templates - for free!* Unlimited asset downloads! Start 7-Day Free Trial
  1. Code
  2. WordPress

Adding Form Validation to WordPress Comments Using jQuery

Scroll to top
Read Time: 13 mins

When it comes to simpler user experience, having your form validation happen instantly on the same page is a lot cleaner than reloading pages and possibly losing some form content. In this tutorial I'll show you how to use jQuery to do some instant checking on an example comment form.

Our Example

For our example we're going to add form validation to a comment form in the default WordPress theme. The process is much the same for any type of form validation however so you could easily apply this technique to a non-WordPress example.
The theme we will add the validation to is WordPress' Default theme that comes packaged with every install. So if you'd like to follow along completely, just head to Wordpress.org and download and install a copy on your server.

If you are unfamiliar with WordPress' comments form, you might also want to visit the NETTUTS tutorial - Unravelling the Secrets of WordPress' Comments.php

Step 1 - Download jQuery & the Bassistance.de Validation Plugin

You can download jQuery at the website jQuery.com On the first page you will directly see "Download jQuery and a few different downloads. We are not going to mess around with the jQuery framework, so you can download the "Minified and Gzipped" version, this means it's compressed.

Next we need the jQuery validation plugin, made by bassistance.de. This plugin allows you to validate web forms, you can download it here. This file contains a few Javascript files, but we only need "jquery.validate.min.js" (also compressed) for this tutorial.

Step 2 - Uploading files

Now you should have 2 files, "jquery.validate.min.js" and "jquery-1.2.6.min.js", we are going to upload this to our WordPress template directory.

Because in this tutorial we are using the default WordPress theme, literally called "default", the folder we need is located in /wp-content/themes/default/.

To keep things organized we will create a new directory called "js", this will be the folder with all the javascript. When you have the directory created, upload the files to the folder we just created. (/wp-content/themes/default/js)

Step 3 - Loading Javascript

Now that we have the javascript uploaded in our directory, we still have to load it into our theme. The javascript should load between the <head> </head> tags. The head tags are located in a php file, that's located in the theme directory.

So search for "header.php", this is the file where the top of the theme code is located. Now we have to make sure we add the javascript before these 2 lines:

This is how we include a javascript file:

Of course when you are creating a WordPress theme for a client, you want to make sure it's easy to install. You don't want to say, "You still have to change the URL to the javascript though!"
We want things to happen automatically, so it's best if we use WordPress tags. To display the URL to the template directory you can use this code:

So in combination with the code to include the javascript, the final result is:

Now these 2 javascript files will be loaded at every page, and can be used on all WordPress pages using this theme!

Step 4 - Activating Validation

Ok, now it's time to activate the comment form validation, so go back into the theme directory, and look for /wp-content/themes/default/comments.php

Now, we only need to take a look at the form part of the code! The form starts at line 73, and it looks like this:

Now as you can see, the form has an ID element, it's called "commentform", we need this name to activate the javascript.
Don't close this file yet, first switch back to "header.php", and add these lines below the jquery.validate.min.js

As you can see, the ID of the form is in there, "#commentform" this activates the validation for any form with the id commentform.
So watch out you don't use duplicate ids or else some forms will be validated, when they perhaps don't need to be.

Now, when you submit a comment currently and you leave all fields blank it does nothing, it still shows the default WordPress error. In the next step I will show you how to start validation for each field.

Step 5 - Name field validation

Now it's time to start the validation for each field. This means going through telling the validation javascript file what kind of validation is required. The validation javascript is so easy to use, you only need to enter a few special words to start the validation. So let's start off with the first field, that's the required name field, the field looks like this:

We want to make sure the commenter has filled in the field, and if possible make sure at least 4 characters are entered. YES! but how? Well this is extremely simple, you can define validation by calling a class. So simply add class="required".

And WTF it works! If you hit submit without typing in your name you get "This field is required." Nice!! So what about if the user doesn't enter a minimum number of characters?
Well we can simply add that validation by adding minlength="4" to the field options:

And now, when you enter something (less then 4 characters) you will see a new message shows up "Please enter at least 4 characters.". So that works perfectly! Minlength allows you to set the minimum amount of characters, just replace the number to what you think is necessary.

Step 6 - Mail field validation

Next we will validate the email field, so this is how the field looks like:

I know what you are thinking, we do just the same as the previous step. Well that would be wrong, because aside from the field simply being required, it also has to be a valid email address. Now we know how to set it required by simply adding class="required", but how to validate the email? Well it's as easy as setting it to be required, except now we just add email.

Huh what? Just add "email", so it becomes class="required email", this makes it required and checks for a valid email:

If you try out the email field, you will notice that it's says "This field is required." when submitted, that's good! And now when you enter something that is not this format: xx@xx.xx it will say "Please enter a valid email address." so that's working perfect! See how easy it is!

Step 7 - Website field validation

Are we going to validate the website field? It's not required right? Yes, you are right! But we do want a valid URL! So we are going to validate a URL, it's just as easy as previous validations but first let's take a look at the URL field:

Now you could set it required and set a minimum amount of characters, but I don't think that's necessary for this field.
I just want a valid URL, so how to? We just add another class but this time we name it class="url", so let's add that:

And what do you know! I enter "blabla" in the website field and it directly returns "Please enter a valid URL.", and when I leave it empty it doesn't say it's required when I submit.
So that's working perfect, just as I wanted! As you can see it's very easy thanks to jQuery and the Validation Plugin.

Step 8 - Comment field validation

That's the last field to validate, now I don't like short spam messages like "click me" and that kind of comments, but I also hate long messages, that take hours to read, or are just full of spam. So I would like a minimum and a maximum amount of characters. But first let's check out the comment field:

Well you know step 1, add the required class (class="required") to make sure something is typed in the textarea. Now the minimum, you remember right? (minlength="") Now I think at least 10 words need to have been typed. So that would be minlength="10", it's still as easy as that. But now we want to set a maximum, but how? Well the plugin has a solution for that, instead of minlength just add maxlength plus the amount of words. I think 100 words are enough so add maxlength="100".

EASY! Yes I know! So this is how it would look:

So now, when you submit the form empty is will say as all other fields "This field is required.", but if you enter less then 10 characters it says "Please enter at least 10 characters." and if you enter more then 100 it says "Please enter at least 10 characters."! So we completed the validation!! But that's not all, we still need to style it!

Step 9 - Form styling

I don't know about you, but I don't like the way the form looks. Its messy and the errors just popup with no style. So we are going style everything so it looks nice & clean, but first I would like to change the label position. As you can see right now, it first shows the "input field" then the "error" and then the "field label".

I think it should look like this "Field label", "input field" and then the "error", to do this we only have to move the label above the html. So let's change the first field from:


As you can see the only thing we did was move the <label> above the <input>. When you now refresh your comments page you will see that the text "Name (required) is moved infront of the input field.
So now repeat this step for all input fields, at the end it should look like this:

Now as you can see, all fields have labels, except the comment field, I think it should have a label. So just do the same, and place a label above the input field:

That doesn't look much better does it? Well that's because we still need to style it! So now it's time to open the theme CSS file. The CSS file for this theme can be found in "/wp-content/themes/default/style.css", just open this file and scroll all the way down.

OK we are set to start styling, but we want to make sure only the form gets affected by this CSS. Thanks to the form id, we can make sure this happens. So in front of each of the CSS lines we add, we'll make sure to type #commentform .classname, this makes sure only fields between the <form></form> are affected.

We are first going to start on the label tag, so add this to the CSS:

Now we can apply CSS to the label, by typing options between the { and }. So first let's set a width, this is how much space it will get, around 200px should be good. You can still read all lines and no text is cut-off.

Now as you can see, nothing happens. This is because we still need to make sure the labels stay left. We can use float for this:

Now that's looking more like it! Now let's style the input fields and the text area.
To apply CSS to those fields we can call them using "input" and "textarea". So let's add that plus a little border:

Now I want all fields to be the same length, as well as the textarea. So we are going to apply a fixed width, like this:

Step 10 - Error styling

Now when you hit submit you will see the error messages don't look very nice. And I think they need to be just below the input fields. When the validation script outputs a error, the html will look like this:

This tells us, generated errors get the class "error", so let's try it out and move the error below the input fields.
Remember the labels are 200px width, so you know we have to margin-left for that amount of pixels:

But that's a bit plain so let's add a background color and a border:

A few things here that make it look bad, the font size, there's no padding (space between text and the gray border) and the margin (space between errors and the fields). Plus it would look much nicer if the error width is the same as the input field, so let's try that:

You can see that I adjusted the width, you always have to tweak things a bit so everything lines up:

That's already looking great, but something is missing! I know a error image! Lets try a famfamfam icon.

Well that's not really it, I think! We have to move the text to the right, we can do this using padding-left:

Always remember that using padding increases the fixed size, so we applied 20 pixels padding to the left, which means we have to subtract 20 pixels from the width. So that's why the I changed the width to 209 (229-20)

And that's it! The jQuery validation plugin is extremely easy to use and apply and you can use this technique on any form, not just WordPress comments forms.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.