Validate WordPress Forms with jQuery

Update (1 Feb 2013): I’ve updated the script here, primarily to jump to the latest version of the bassistance plugin.

This article will teach you how to add validation to your WordPress comment forms, using jQuery.

With validation, users can submit their comment and instantly see if they’ve hit an issue. There is no need to submit the page and get WordPress’ default “There is a problem…” page. Instead, errors are displayed inline instantly.

In our example, we will build a plugin which you can drop into any theme and will work instantly.

Just like last week, you can see the finished product in action on the demo site. And you can download the completed files here.

Organize Your Files

Download the bassistance.de form validation plugin for jQuery.

This plugin contains the file jquery.validate.min.js, which will be taking care of all our validation worries for us. All we have to do is tell it how and when to work.

I’ve called the plugin “pbd-validate-comments”, though you’re welcome to name it however you like. You should have a .php file with the same name, and then a “css” and “js” folder. Create a style.css file in the css folder, and place the jquery.validate.min.js file from above in the js folder.

The end result is like this:

Files

With your files in place, open up the pbd-validate-comments.php file and start with the essential plugin info:

1
2
3
4
5
6
7
8
9
10
<?php
/**
 * Plugin Name: PBD Validate Comments
 * Plugin URI: http://www.problogdesign.com/
 * Description: Validate comments instantly with jQuery. Uses <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/">jQuery Form Validation</a> plugin by Jörn Zaefferer.
 * Version: 0.2
 * Author: Pro Blog Design
 * Author URI: http://www.problogdesign.com/
 * License: GPLv2
 */

Load Your Scripts

Now, let’s begin. The process today is quite simple, and will have 3 steps.

  1. Load all of our scripts.
  2. Initialize the validation on our form, and tell it the rules to use.
  3. Style the error messages.

Let’s start with loading the scripts. Still in pbd-validate-comments.php, paste the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
 * Add jQuery Validation script on posts.
 */
function pbd_vc_scripts() {
	if(is_single() ) {
		wp_enqueue_script(
			'jquery-validate',
			plugin_dir_url( __FILE__ ) . 'js/jquery.validate.min.js',
			array('jquery'),
			'1.10.0',
			true
		);
 
		wp_enqueue_style(
			'jquery-validate',
			plugin_dir_url( __FILE__ ) . 'css/style.css',
			array(),
			'1.0'
		);
	}
}
add_action('template_redirect', 'pbd_vc_scripts');

The important thing here is the wp_enqueue_script() section. This is what tells WordPress to load in our validation script. Similarly, wp_enqueue_style() is used to load our stylesheet.

We have then wrapped that up in an is_single() condition, so that our script is only loaded on post pages. And in order for that to work, we have put the whole thing in a hook (Attached to ‘template_redirect’).

The end result is that our script is now loaded on every post page, but not on the homepage/categories etc.

Activate the Script

Congrats, you’ve loaded in the scripts now. The next step is to initialize the validator and give it our rules.

One way to give the rules is to use CSS classes, e.g. class=”required” would mean the field is required.

However, with new themes using the comment_form() function, that gets more complicated. So instead, we will pass all of the rules via JavaScript.

Carry on in the PHP file, and paste the following:

1
2
3
4
5
6
7
8
9
/**
 * Initiate the script.
 * Calls the validation options on the comment form.
 */
function pbd_vc_init() { ?>
	<script type="text/javascript">
		jQuery(document).ready(function($) {
 
			$('#commentform').validate({

Here, we open a new function (Which we will hook into place on the page in a minute), and start writing some JavaScript.

The ‘#commentform‘ needs to be a jQuery selector for your form. In most cases, you can leave this as it is because 99% of WordPress themes will be using that ID on their comment forms.

We are now going to pass in an array of options. The first will be an array of rules. You can see the full list of validation rules available here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
rules: {
	author: {
		required: true,
		minlength: 2
	},
 
	email: {
		required: true,
		email: true
	},
 
	url: {
		url: true
	},
 
	comment: {
		required: true,
		minlength: 20
	}
},

We have simply taken rules from the available list, and applied them to the various fields (author, email etc. are the “name” values for the comment form fields, and will be in every WordPress theme).

These rules translate to:

  • Author Field – Must be filled in, with a minimum of 2 characters.
  • Email Field – Must be filled in, with a valid email address.
  • URL Field – Not required, but if something is entered, it must be a valid URL.
  • Comment Field – Required, and must be at least 20 characters long.

How simple was that?

We could leave it there, but let’s pass in one more option; a custom error message for each field.

1
2
3
4
5
6
messages: {
	author: "Please enter a valid name.",
	email: "Please enter a valid email address.",
	url: "Please use a valid website address.",
	comment: "Message must be at least 20 characters."
}

Again, this is quite self-explanatory. The messages entered will appear when there is an error in the corresponding field.

Now, just close up the JavaScript functions and the script tag, and then hook the PHP function into place.

1
2
3
4
5
6
7
			});
		});
	</script>
<?php }
add_action('wp_footer', 'pbd_vc_init', 999);
 
?>

And that’s the end of our work, so we’ve closed up the PHP file!

Last of All, Some Styles

If you save and activate the plugin now, it all works perfectly well. However, a little CSS for the error messages won’t hurt.

Open the style.css file, and paste the following:

1
2
3
4
5
label.error {
	display: block;
	background: #ffd2d2;
	padding: 0 10px;
}

And that’s it! Save your plugin, activate it in the dashboard and go try posting some phony comments. You should see instant errors pointing out any issues.

The jQuery validation script is hugely powerful and suitable for just about any type of form. Once you know how to use it in WordPress as we have done here, you’ll find you can use it anywhere!

And don’t forget, if you don’t want to put the files together yourself, you can grab the completed download here.

Please let me know if you enjoyed this post! If you’d like to see more jQuery guides on the site, leave a comment!

The idea behind this post was a collaboration between myself, Michael Martin, and Seth Bryant, thanks Seth!

Enjoy this post? You should follow me on Twitter!