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.
Adding Form Validation to WordPress Comments using jQuery
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.
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. 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:
#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.
|