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:
<?php wp_head(); ?> </head>
This is how we include a javascript file:
<script src="url/to/javascript" type="text/javascript"></script>
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:
<?php bloginfo('stylesheet_directory'); ?>
So in combination with the code to include the javascript, the final result is:
<script src="<?php bloginfo('stylesheet_directory'); ?>/js/jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="<?php bloginfo('stylesheet_directory'); ?>/js/jquery.validate.min.js"" type="text/javascript"></script>
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:
<form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php" method="post" id="commentform">
<?php if ( $user_ID ) : ?>
<p>Logged in as <a href="<?php echo get_option('siteurl'); ?>/wp-admin/profile.php"><?php echo $user_identity; ?></a>. <a href="<?php echo get_option('siteurl'); ?>/wp-login.php?action=logout" title="Log out of this account">Log out »</a></p>
<?php else : ?>
<p><input type="text" name="author" id="author" value="<?php echo $comment_author; ?>" size="22" tabindex="1" />
<label for="author"><small>Name <?php if ($req) echo "(required)"; ?></small></label></p>
<p><input type="text" name="email" id="email" value="<?php echo $comment_author_email; ?>" size="22" tabindex="2" />
<label for="email"><small>Mail (will not be published) <?php if ($req) echo "(required)"; ?></small></label></p>
<p><input type="text" name="url" id="url" value="<?php echo $comment_author_url; ?>" size="22" tabindex="3" />
<label for="url"><small>Website</small></label></p>
<?php endif; ?>
<!--<p><small><strong>XHTML:</strong> You can use these tags: <code><?php echo allowed_tags(); ?></code></small></p>-->
<p><textarea name="comment" id="comment" cols="100%" rows="10" tabindex="4"></textarea></p>
<p><input name="submit" type="submit" id="submit" tabindex="5" value="Submit Comment" />
<input type="hidden" name="comment_post_ID" value="<?php echo $id; ?>" />
</p>
<?php do_action('comment_form', $post->ID); ?>
</form>
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
<script type="text/javascript">
$().ready(function() {
// validate the comment form when it is submitted
$("#commentform").validate();
});
</script>
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:
<p><input type="text" name="author" id="author" value="<?php echo $comment_author; ?>" size="22" tabindex="1" /> <label for="author"><small>Name <?php if ($req) echo "(required)"; ?></small></label></p>
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”.
<p><input type="text" name="author" id="author" value="<?php echo $comment_author; ?>" size="22" tabindex="1" class="required" /> <label for="author"><small>Name <?php if ($req) echo "(required)"; ?></small></label></p>
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:
<p><input type="text" name="author" id="author" value="<?php echo $comment_author; ?>" size="22" tabindex="1" class="required" minlength="4" /> <label for="author"><small>Name <?php if ($req) echo "(required)"; ?></small></label></p>
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:
<p><input type="text" name="email" id="email" value="<?php echo $comment_author_email; ?>" size="22" tabindex="2" /> <label for="email"><small>Mail (will not be published) <?php if ($req) echo "(required)"; ?></small></label></p>
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:
<p><input type="text" name="email" id="email" value="<?php echo $comment_author_email; ?>" size="22" tabindex="2" class="required email" /> <label for="email"><small>Mail (will not be published) <?php if ($req) echo "(required)"; ?></small></label></p>
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:
<p><input type="text" name="url" id="url" value="<?php echo $comment_author_url; ?>" size="22" tabindex="3" /> <label for="url"><small>Website</small></label></p>
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:
<p><input type="text" name="url" id="url" value="<?php echo $comment_author_url; ?>" size="22" tabindex="3" class="url" /> <label for="url"><small>Website</small></label></p>
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:
<p><textarea name="comment" id="comment" cols="100%" rows="10" tabindex="4"></textarea></p>
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:
<p><textarea name="comment" id="comment" cols="100%" rows="10" tabindex="4" class="required" minlength="10" maxlength="100" ></textarea></p>
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:
<p><input type="text" name="author" id="author" value="<?php echo $comment_author; ?>" size="22" tabindex="1" class="required" /> <label for="author"><small>Name <?php if ($req) echo "(required)"; ?></small></label></p>
To:
<p><label for="author"><small>Name <?php if ($req) echo "(required)"; ?></small></label> <input type="text" name="author" id="author" value="<?php echo $comment_author; ?>" size="22" tabindex="1" /></p>
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:
<label for="comment"><small>Comment</small></label></p> <p><textarea name="comment" id="comment" cols="100%" rows="10" tabindex="4"></textarea></p>
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:
#commentform label{
}
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.
#commentform label{
width: 200px;
}
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:
#commentform label{
width: 200px;
float:left;
}

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:
#commentform input, #commentform textarea{
border: 1px solid #dbd8d3;
}

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:
#commentform input, #commentform textarea{
border: 1px solid #dbd8d3;
width: 225px;
}

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:
<label class="error" generated="true" for="author">This field is required.</label>
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:
#commentform label.error{
margin-left: 200px;
}

But that’s a bit plain so let’s add a background color and a border:
#commentform label.error{
margin-left: 200px;
background: #fbfcda;
border:1px solid #dbdbd3;
}

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:
#commentform label.error{
font-size: 11px;
margin-left: 200px;
background: #fbfcda;
border:1px solid #dbdbd3;
width:229px;
margin-top:4px;
}
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.
#commentform label.error{
font-size: 11px;
margin-left: 200px;
background: #fbfcda url('images/cancel.png') no-repeat left;
border:1px solid #dbdbd3;
width:229px;
margin-top:4px;
}

Well that’s not really it, I think! We have to move the text to the right, we can do this using padding-left:
#commentform label.error{
font-size: 11px;
margin-left: 200px;
background: #fbfcda url('images/cancel.png') no-repeat left;
border:1px solid #dbdbd3;
width:209px;
margin-top:4px;
padding-left:20px;
}
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.










wow! great tutorial. thanks
This is such a cool way to include client-side validation, and very user friendly.
One thing I have noticed though, textarea name does not include the attributes ‘minlength’ & ‘maxlength’:
http://www.w3.org/TR/html401/interact/forms.html#edef-TEXTAREA
And therefore fails xhtml validation. Does anyone know a way around this issue?
I’m wondering about this, too.
The methodology is great, but it would be greater if it can help the code pass xhtml validation.
stimulating and informative, but would participate in something more on this topic?
yeah,a good example! trying it!
Your site does not correctly work in safari browser
Very Nice Tutorial.
I like those detailed things
test my avatar
test your reply
I think it’s not pretty.
Great tutorial, verry helpful! But, is there some way you can only make the border red?
Hey really dig the way all this stuff works. I’m completely new to java, I can hard type html and have used flash, I’m wondering the best way to learn this. Seems these tutes are a help but these are so many gaps in my knowledge. Are there any good books? or what would people think is the best way to learn?
Thanks in advance, great site, Cheers
Thanks for sharing it!
@Steven: Yeah you can do so by changing the color in # tag of border.
Earlier code:
#commentform label.error{
font-size: 11px;
margin-left: 200px;
background: #fbfcda url(‘images/cancel.png’) no-repeat left;
border:1px solid #dbdbd3;
width:209px;
margin-top:4px;
padding-left:20px;
}
New Code for you:
#commentform label.error{
font-size: 11px;
margin-left: 200px;
background: #fbfcda url(‘images/cancel.png’) no-repeat left;
border:1px solid #ef1611;
width:209px;
margin-top:4px;
padding-left:20px;
}
You can change the color as you wish. I’ve done a sample one for you.
Thanks for your help, but I meaned that the “This field is required.” won’t display, that only the name, email and comment field will get a red border.
Useful, thanks.
G’day Philo from Australia
I have been trying for two days to get this to work on a simple form (NOT the Comment Form) on my wordpress blog with no luck at all?
I only want it to validate the first name field (fname) – that’s it.
Does it work on all themes? The one I use has a tabbed sidebar script in the js folder. Could that be conflicting with this script?
Thanks for your time. Excellent explanation – but I would like to have seen how it works with other forms as well.
Dave
thank you so much! i will review it and try it on my web. thanks a lot!
А интересно, если текст c вашего сайта себе копировать, ссылку куда лучше ставить прямо на эту запись блога или же на главную страницу.
Your Message…Add Your Comment
( GET A GRAVATAR )
Man, I love U
:D:D
Respect!!!
This is exactly what i needed, this tutorial is golden!
thank you , i have a question about Jquery form validation
how could i execute the Jquery form validation code before form action?
when i press submit it dose not chick the fields.
its very usefulll.. great..
Preview
I agree with Ahmed…even though it validates the form(and shows the error msg) when you click the submit button, it still gets redirected to wp-comments-post.php
I am also having the same problem as Gopal. On submit the form flashes the error message, but still continues the submit and redirect to wp-comments-post.php
WP2.7.1 using jquery 1.3.1
Да, было бы смешно, если б к сожалению не было так грустно …
Hi, great tutorial but i wonder why you didn’t implement wp_enqueue_script(‘jquery’);.
Btw, I tried using it but I ended up adding jquery into my theme. I wanted to use the bundled jquery in Wordpress but it seems like it’s no luck for me.
Again, great tutorial
as
hello, i don`t know why after applying correctly it`s not working
test ajax
Error: $(“#commentform”).validate is not a function
Source File: http://192.168.1.12/project/wordpress/test-cstm-field/
Line: 21
Thanks for this tut!
However, if anyone has problem, try this one:
http://wordpress.org/extend/plugins/comment-validation/
It’s not working for me either.
Keeps going to the wp-comments-post.php page
What is the fix for this?
Wow! Great stuff to save my life when i am trying to edit the comment form of my website http://www.the-evault.com. I am a newbie to Wordpress, trying hard to learn it. Keep the hard work! cheers!
Российский аукцион – это вид internet аукциона, при котором товар или услуга выставляется на продажу по минимальной стоимости. Участники аукционных торгов делают ставки с фиксированным шагом. Победителем интернет аукциона считается участник, сделавший последнюю ставку. Регистрация на интернет аукционе бесплатна + 500 рублей на счет!
Same issue than some people. Still go to wp-comments-post.php. Is it normal? Any ideas how to make that work?
Hmm. OK I sppose
I have definitely seen a big difference in speed using a ext4 system. ,
Cool=) Realy need article!
I have a lightbox-2 plugin in wordpress activated.
I tried to apply the validation technique above.. Doesn’t work.
When I deactivate the lightbox-2 plugin then it works..
Any help how to figured it out.. I need my lightbox-2 activated.
same issue, it gets redirected to wp-comments-post.php
Formerly your next shindy or http://teakrefinishing.blogspot.com – teak furniture refinishing festive enterprise arrives, we make amends move aside your teak gear look like new. Craft was in additional ditch-water exchange for seven years and has been in brackish sea water looking for six years. But where you start depends on your budget and your tastes.
It was certainly interesting for me to read that article. Thanks for it. I like such themes and anything connected to this matter. I definitely want to read more soon.
@Sarah, you look like you know what you are talking about. Would you mind sending me your mail address? I would like to talk more with you.
very nice patch
Is it possible to add a validation in the comment field that does NOT allow users to submit their email address in the comment? It attracts spam harvesters and drives me crazy when people don’t read the comment policy about not to do so.Here are the formats they typically give it in:
email@domain.com “email2 AT domain2.com” “email3 AT domain3 DOT com” “email4[at]domain4[dot]com” etc…
Would appreciate any help you can give as far as how to code this! Thanks!