Comment form validation creates a friendly user experience. When using the default wordpress comment system, if the user doesn’t fill out all the require fields, they are redirected to a new page displaying an error message.
The user now has to press the ‘back’ button in their browser window and they may or may not lose information they have already entered in.
To solve this problem, i’ll show you how jQuery can be used so comment form errors are displayed to the user without leaving the page.
To keep the page loading times fast, we are going to use the minified versions of jQuery and jQuery Validate from the Google and Microsoft CDN servers. Let’s only load the required code if any single post is being displayed – and if comments are open.
Open your theme function.php file and add :
function comment_validation_init() {
if(is_singular() && comments_open() ) { ?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#commentform').validate({
onfocusout: function(element) {
this.element(element);
},
rules: {
author: {
required: true,
minlength: 2,
normalizer: function(value) { return $.trim(value); }
},
email: {
required: true,
email: true
},
comment: {
required: true,
minlength: 20,
normalizer: function(value) { return $.trim(value); }
}
},
messages: {
author: "Please enter in your name.",
email: "Please enter a valid email address.",
comment: "Message box can't be empty!"
},
errorElement: "div",
errorPlacement: function(error, element) {
element.before(error);
}
});
});
</script>
<?php
}
}
add_action('wp_footer', 'comment_validation_init');
Now let’s go over the code and it’s options.
The onfocusout section
This enables “real time” validation. If you prefer to only validate -after- the user clicks on the “Post Comment” button, just remove that entire section.
The rules section
- Author – required field with a minimum length of 2 characters.
- Email – required field with a valid email address.
- Comment – required field with a minimum length of 20 characters.
They can easily be adjusted to anything you want. Change “true” to “false” to remove validation for any field.
The “normalizer” option in the rules section is used to trim any whitespace from the user input. This way, for example, (20) white spaces for a comment won’t validate.
The messages section
This is where you control the error message you would like to be displayed when :
- The form field is not vaild.
- The user does not fill in the required field.
The errorElement option sets the error message to be displayed in a html <div> section. This is done so the error message doesn’t mis-align any of the form boxes.
The errorPlacement options sets where you want the message to be displayed. It’s currently set to display the message -above- the invalid form element.
All there is left to do is add a little color to the error messages. Open your theme style.css file and add :
[css]#commentform .error { font-size: 12px; padding: 0 0 5px 0; color: #FF0000; }
#commentform input.error, #commentform textarea.error { background: #FFD2D2; color:#000000; }[/css]
The end result should look like this :
That’s it! You now have a lightweight jQuery comment form validation that works for Microsoft Edge, Internet Explorer, Firefox and Google Chrome.
Let me know in the comments if this has helped you out and if you would like a jQuery tutorial on something else!
Wow … this is great! It took me literally 30 seconds to get it running on my site. I really hated the fact commenters had to press the ‘back button’ on any validation error. This solves the issue perfectly …
Glad I could help!
Great!, so many thanks.
I had to replace your add_action with:
add_action(‘wp_print_scripts’, ‘comment_validation_init’);
Hi Dave Hannon.
Thank you very much for the tutorial. It helps me a lots.
Hi Dave,
Thanks for the tutorial, it was exactly how I wanted to implement jQuery validate into WordPress!
Thanks for the tutorial,.. I did extraly what you have here but my page won’t use the css for the class “error”. The error message switched to the top of the elements of my form but the letters remain grey . Any help would be appreciated. By the way, I am using bootstrap with a WordPress template.
@sam – try this instead :
div.error { font-size: 12px; padding: 0 0 5px 0; color: #FF0000; }
Let me know if that works for you.
Thanks for the quick response Dave. I was able to make it work and actually what I needed was to clear the cache of my browser lol.
Thanks for the tutorial
You’re welcome and thanks for letting me know!
thanks
Thank you … soo much…
thanks for it !!!
Time savor!
Thanks
Can this also work for multiple forms on a page, if I give each form a different id? Or what do I have to do to make this work?
Yes, you just need to add the form ID names to this line :
Find:
$(‘#commentform’).validate
Replace:
$(“#commentform, #newform, #anotherform”).validate
Hi Dave,
Ok, thank you but how can I do this if I give each commentform the ID of the PostID, like #commentform1022 for postID 1022 and for example #commentform1038 for postID 1038 and so on….
There can be many commentforms on a page which all get the ID of the posts on that page!
Thanks for this helpful script, you saved me tons of time, keep up the good work, cheers
This worked great on the single page but not on a custom post page that I aded a loop and the comment form to. I took out the is_single conditional. Is there something else that I’m not considering? Thanks for this.
@Amelia – You can try this (from the WordPress codex) : To check for all the post types, use the is_singular() function.
So just replace is_single() with is_singular().
what about messages like this
“Duplicate comment detected; it looks as though you’ve already said that!”
This is amazing Dave, i hated the default error display by WordPress. Am smiling as it saved me a lot of time, keep up cheers!
Solid tutorial, suggestion though:
Why wait until the user clicks submit (at least this is how it’s behaving for me)? Trigger validation in real time by adding:
onfocusout:function(element){if( !this.checkable(element) ){ this.element(element); } }
to the validate() call. Also, my knowledge may be incomplete, but why not add this to a js file instead? I’ve done so and it seems to accomplish the same result with the advantage of being tidier.
Great tutorial nonetheless.
I used it. It’s work’s fine , thanks a lot.
“The error message mis-align the form boxes.”– I was trying to fix this for the long time.. Thanks a lot for your post .
This is amazing Dave, i hated the default error display by WordPress. Am smiling as it saved me a lot of time, keep up cheers!
thank u very much ……i get my result today……..
This was very helpful and easy to implement! Not sure why this isn’t the default for WordPress. Such a bad design to bring the user to a new page to display form errors.
Wow! so simple! thanks a lot!
Hey …. thanking you …. thank you very much.. You saved my lot of time.
wow, thanks a lot …
Hi,
Hannon, thanks for this code and this is what I want.
One more feature that I want, how to check captcha validation with you code, I know the condition for blank captcha field validation but what about if the user can add the wrong captcha, is this possible to check wrong captcha validation with your code.
thanks
sorry if I’m too late to reply, just wanted to know how did you do this? I’m trying to find this solution for my site.
I try with this code ;
rules: {
“recaptcha-checkbox”: {
required: true,
minlength: 1
}
}
messages: {
“recaptcha-checkbox”: “check the recaptcha box”
},
But didn’t work, still displaying to a new page whenever someone did not check the checkbox.
@Nimesh: no, I don’t believe that’s possible.
ok no problem, and again thanks for this validation help.
I’ve updated the code so it uses the latest versions of jQuery and jQuery Validate + modified the code so it does validation in real time.
If you do not want to validate in real time, simply remove the “onfocusout” section – then it will only validate after you press the “Post Comment” button.
Great!,
thanks.
Super!!!! Thank you very much
Great! so many thanks.
Good. Keep it up.
Hi,
The above code works very well. But I need help in validating Mobile Number field. I have created a new field – Mobile. It has some regex format say /0,1[1-9]/. The above code you gave is not validating this newly created field. Can you help me to solve this?
Thanks
@renu – Something like this should work :
Find :
jQuery(document).ready(function($) {
Add After :
$.validator.addMethod(
“regex”,
function(value, element, regexp) {
var check = false;
return this.optional(element) || regexp.test(value);
},
“Please check your input.”
);
Then use this to validate the phone number :
telephone: {
required: true,
regex : /^[\d\s]+$/,
minlength: 7
},
I added, but its worked fine in Firefox but other browser it’s not over written. It work different in different browser. Is it depend on browser?
@Halder – Which browser is it not working on for you? I just tried IE, FireFox, Chrome & Edge and it’s working fine here.
I added it into functions.php file. But it’s not working any browser. What happen i don’t understand. Please Help me.
I change only errorElement: “div” to errorElement: “p”.
I added, but its worked fine in Firefox but other browser it’s not over written. It work different in different browser. Is it depend on browser?
@Debasish – why did you change the errorElement? It needs to be a “div” or things will get mis-aligned.
@mlll – no, it works in any browser. You probably need to clear your temporary internet files and refresh the page.
It is amazing!! Thank you very much…
thanks its work for me ! its amazing.
and the html…?
@rose19 – The entire code needed for this to work is listed at the top of this page.
I paste the code at the top of this page into the function.php.. but what i’m writing in my form (html)?
@rose19 – You don’t write anything in your form, all this code belongs in your function.php file and css file (for styling).
Thanks Dave…it was very helpful..saved me a lot of time… gracias amigo..!!!
Hello Sir,
I am very to implement your code and it works in first time. Good Job. Thanks.
Great tutorial but one thing what about spaces in comment box and name, it allows to submit but next page error shows up
You need to add a normalizer to the comment rules section.
The normalizer will trim the value (get rid of the white space) before validating.
comment: {
required: true,
minlength: 2,
normalizer: function(value) { return $.trim(value); }
}
More information here : https://jqueryvalidation.org/normalizer/
thank you so much for quick response it worked like a charm
You’re welcome!
I’ve updated the article with this new code + the new jQuery Validation version link.
http://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js
Thank you for sharing this! I spent hours trying other suggestions, but some didn’t do quite what I wanted, and others didn’t work at all. A more knowledgeable person probably could have made them work, but I needed a solution that worked without much tinkering on my part. This one is perfect, and no tinkering was required at all!
It seems I spoke a little too soon. The validation works great, but I will need to do a little tinkering. Now the background color of the form shows for just a split second in the input fields, too. Also, there’s a small jump when the error message goes away as the user is typing. Still, this validation is lightyears better than WordPress’s ugly error page.
Can you provide me a link to your blog so I can have a look at what is going on?
Thank you so much for the offer, but it turns out that the background issue wasn’t related to your code. It does it at certain times, and I just hadn’t noticed it before. Sorry for the false alarm.
No problem! You may want to try different a web browser(s) and see if the issue persists.
Thank for help.
Works with 5.1 perfectly.
Although I have been forced to update the url’s
… https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
… https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js
Thank you so much
Thanks for letting me know!
I’ll update the post with the new URL’s later today.
Thank you very much. But how to check also if the form checkbox of wp-comment-cookies-consent is checked? The code below don’t work, am I missing something?
wp-comment-cookies-consent: {
required: true,
},
Hi Max,
Any class or id’s that contain non-alphanumeric characters needs to be enclosed with quotes.
“wp-comment-cookies-consent”: {
required: true,
minlength: 1
},
and
messages: {
author: “Please enter in your name.”,
email: “Please enter a valid email address.”,
comment: “Message box can’t be empty!”,
“wp-comment-cookies-consent”: “You must consent to our cookie!”
},
Hope this helps!
THANK YOU for this, spent hours trying to find a working solution for my site. This one works beautiful on my site.
I got a question though, I just recently adding recaptcha v2 to my comment form, but when the checkbox is not checked, the error message display on a new page (the same error message page as comment validation before using this code).
How do I make/modified this code to also display recaptcha error message below recaptcha badge?
Again, thank you for this amazing code.
I’m not sure it can be done. I don’t use recaptcha on this website.
I saw you replied to someone else as well, and my suggestion is to try using your code – but use the ID of the checkbox “recaptcha-anchor” instead of the class name “recaptcha-checkbox” and see if that works for you.
Thank you for the reply. I tried using “recaptcha-anchor” and several parents id’s, but none of them works.
Maybe you’re right, i can’t be done. But thanks anyway, maybe someday if you figure out how to accomplish that, let me know. Again, thanks.
Hello;
Thank you for the code and the easy to get article.
i have used the code but it doesn’t work for me witch i guess it could be because i have used another code to recreate my form to my liking and now i can not use your code;
It would be grate if you could help me to fix it
the code i have used for my form is at the end of this article:
https://developer.wordpress.org/reference/hooks/comment_form_fields/
thanks in advance.
I’m not seeing anything there that would cause your issue.
Could you please give me a link to your blog so I can have a look?