Comment Validation for WordPress

Client side validation is easy to use and can increase your website’s performance by preventing unnecessary requests to your server. Learn how to apply some simple checks to validate your blog’s comment section by reading the rest of the article.

Introduction

I noticed the other day that WordPress does not validate comments before they are sent to the server. It can be irritating for a user to fill out a comment form only to find out after they submit the comment that a field was not filled out correctly. We can improve our user’s experience and increase the site’s performance by using client side validation. It is much faster to perform validation on the client rather than on the server. We can provide instant feedback to our users as opposed to having them wait for the server to receive and process the request.

Please remember that although it can be faster to validate some criteria on the client you will always need to re-validate the data on the server because it is very easy to bypass client side validation (which can be a security concern).

The code

$(function(){	
	validateCommentForm();
});

function validateCommentForm() {
	var commentVars = [$('#author'), $('#email'), $('#url'), $('#comment')];
	submitValidation(commentVars);
	removeErrorOnFocus(commentVars);
}

function submitValidation(commentVars){
	$('#commentform').submit(function() {	
		var valid = true;
		for(x = 0, length = commentVars.length; x < length && valid === true; x++) {
			valid = isNotBlank(commentVars[x], 'Required field') && removeScript(commentVars[x], 'Scripts are not allowed');
		}
		return valid;
	});
}

function removeErrorOnFocus(commentVars){
	if(commentVars){
		for(x = 0, length = commentVars.length; x < length; x++){
			$(commentVars[x]).focus(function(){
				if($(this).next().hasClass('errorMessage')){
					$(this).next().remove();
				}
			});
		}
	}	
}

function errorMessage(element, message) {
	if(!element.next().hasClass('errorMessage')) {	
		element.after(''+message+'');
	}
}	

//===== Validation checks below =====

function isNotBlank(element, message){
	var result = false;
	if(element.val()){
		result = true;
	}else{
    	errorMessage(element, message);
	}
	return result;
}

function removeScript(element, message){
    var string = element.val().replace(/)<[^<]*)*/gi,''),
    result = false;
    if(string == element.val()){
        result = true;
    }else{
        errorMessage(element, message)
        element.val(string);
    }
    return result;
}

I did two validation checks in the code posted above. I did one check to ensure that all of the fields have been filled prior to being submitted. I also included a function to prevent malicious scripts from being added to your website. Feel free to add additional checks to the code posted above. If you need any help adding them please leave a comment below.

Check out the Demo