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!
Barry says
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 …
Dave says
Glad I could help!
Ciro says
Great!, so many thanks.
Marco says
I had to replace your add_action with:
add_action(‘wp_print_scripts’, ‘comment_validation_init’);
Xuan-Loi Vu says
Hi Dave Hannon.
Thank you very much for the tutorial. It helps me a lots.
Adam Mould says
Hi Dave,
Thanks for the tutorial, it was exactly how I wanted to implement jQuery validate into WordPress!
sam says
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.
Dave Hannon says
@sam – try this instead :
div.error { font-size: 12px; padding: 0 0 5px 0; color: #FF0000; }
Let me know if that works for you.
sam says
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
Dave Hannon says
You’re welcome and thanks for letting me know!
velu says
thanks
arun says
Thank you … soo much…
Avadhesh Bhatt says
thanks for it !!!
testor says
Time savor!
Thanks
Martin says
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?
Dave Hannon says
Yes, you just need to add the form ID names to this line :
Find:
$(‘#commentform’).validate
Replace:
$(“#commentform, #newform, #anotherform”).validate
Martin says
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!
festus says
Thanks for this helpful script, you saved me tons of time, keep up the good work, cheers
amelia says
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.
Dave Hannon says
@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().
kamlesh says
what about messages like this
“Duplicate comment detected; it looks as though you’ve already said that!”
Victor says
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!
Josh Weikel says
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.
shihab says
I used it. It’s work’s fine , thanks a lot.
Pughalveni says
“The error message mis-align the form boxes.”– I was trying to fix this for the long time.. Thanks a lot for your post .
Pooja Rathour says
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!
vinoth says
thank u very much ……i get my result today……..
Jonathan says
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.
Anna says
Wow! so simple! thanks a lot!
Robin Thomas says
Hey …. thanking you …. thank you very much.. You saved my lot of time.
frans says
wow, thanks a lot …
Nimesh says
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
owem says
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.
Dave Hannon says
@Nimesh: no, I don’t believe that’s possible.
Nimesh says
ok no problem, and again thanks for this validation help.
Dave Hannon says
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.
pravin says
Great!,
thanks.
Techie says
Super!!!! Thank you very much
Eduard says
Great! so many thanks.
Neharika says
Good. Keep it up.
Renu says
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
Dave Hannon says
@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
},
Halder says
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?
Dave Hannon says
@Halder – Which browser is it not working on for you? I just tried IE, FireFox, Chrome & Edge and it’s working fine here.
Debasish Halder says
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”.
mlll says
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?
Dave Hannon says
@Debasish – why did you change the errorElement? It needs to be a “div” or things will get mis-aligned.
Dave Hannon says
@mlll – no, it works in any browser. You probably need to clear your temporary internet files and refresh the page.
yaicu says
It is amazing!! Thank you very much…
janki says
thanks its work for me ! its amazing.
rose19 says
and the html…?
Dave Hannon says
@rose19 – The entire code needed for this to work is listed at the top of this page.
rose19 says
I paste the code at the top of this page into the function.php.. but what i’m writing in my form (html)?
Dave Hannon says
@rose19 – You don’t write anything in your form, all this code belongs in your function.php file and css file (for styling).
Aroon 5 says
Thanks Dave…it was very helpful..saved me a lot of time… gracias amigo..!!!
sandeep kamara says
Hello Sir,
I am very to implement your code and it works in first time. Good Job. Thanks.
Zed606 says
Great tutorial but one thing what about spaces in comment box and name, it allows to submit but next page error shows up
Dave Hannon says
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/
Zed606 says
thank you so much for quick response it worked like a charm
Dave Hannon says
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
Violet says
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!
Violet says
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.
Dave Hannon says
Can you provide me a link to your blog so I can have a look at what is going on?
Violet says
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.
Dave Hannon says
No problem! You may want to try different a web browser(s) and see if the issue persists.
Selim Reza says
Thank for help.
Sergio says
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
Dave Hannon says
Thanks for letting me know!
I’ll update the post with the new URL’s later today.
Max says
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,
},
Dave Hannon says
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!
owem says
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.
Dave Hannon says
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.
owem says
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.
Hefazat says
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.
Dave Hannon says
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?