Qcybb

We are here to help you solve your problems!

You are here: Home / WordPress / Comment Form Validation for WordPress

Comment Form Validation for WordPress

August 7, 2012 75 Comments

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 :

WordPress Comment Form Validation

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!

Filed Under: WordPress

Leave a Comment ↓

Comments

  1. Barry says

    January 16, 2013 at 6:55 pm

    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 …

    Reply to this Comment
  2. Dave says

    January 19, 2013 at 11:21 am

    Glad I could help!

    Reply to this Comment
  3. Ciro says

    May 19, 2013 at 7:45 pm

    Great!, so many thanks.

    Reply to this Comment
  4. Marco says

    July 5, 2013 at 12:50 am

    I had to replace your add_action with:
    add_action(‘wp_print_scripts’, ‘comment_validation_init’);

    Reply to this Comment
  5. Xuan-Loi Vu says

    July 20, 2013 at 3:53 am

    Hi Dave Hannon.
    Thank you very much for the tutorial. It helps me a lots.

    Reply to this Comment
  6. Adam Mould says

    September 30, 2013 at 1:20 pm

    Hi Dave,

    Thanks for the tutorial, it was exactly how I wanted to implement jQuery validate into WordPress!

    Reply to this Comment
  7. sam says

    October 5, 2013 at 7:52 pm

    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.

    Reply to this Comment
  8. Dave Hannon says

    October 6, 2013 at 10:48 am

    @sam – try this instead :
    div.error { font-size: 12px; padding: 0 0 5px 0; color: #FF0000; }

    Let me know if that works for you.

    Reply to this Comment
  9. sam says

    October 6, 2013 at 4:35 pm

    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

    Reply to this Comment
  10. Dave Hannon says

    October 6, 2013 at 8:22 pm

    You’re welcome and thanks for letting me know!

    Reply to this Comment
  11. velu says

    November 14, 2013 at 11:46 pm

    thanks

    Reply to this Comment
  12. arun says

    November 18, 2013 at 10:42 pm

    Thank you … soo much…

    Reply to this Comment
  13. Avadhesh Bhatt says

    November 20, 2013 at 4:24 am

    thanks for it !!!

    Reply to this Comment
  14. testor says

    December 19, 2013 at 1:32 am

    Time savor!

    Thanks

    Reply to this Comment
  15. Martin says

    January 10, 2014 at 6:52 am

    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?

    Reply to this Comment
  16. Dave Hannon says

    January 13, 2014 at 2:37 pm

    Yes, you just need to add the form ID names to this line :

    Find:
    $(‘#commentform’).validate

    Replace:
    $(“#commentform, #newform, #anotherform”).validate

    Reply to this Comment
  17. Martin says

    January 20, 2014 at 3:21 am

    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!

    Reply to this Comment
  18. festus says

    February 6, 2014 at 6:00 am

    Thanks for this helpful script, you saved me tons of time, keep up the good work, cheers

    Reply to this Comment
  19. amelia says

    February 7, 2014 at 10:41 am

    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.

    Reply to this Comment
  20. Dave Hannon says

    February 8, 2014 at 12:30 pm

    @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().

    Reply to this Comment
  21. kamlesh says

    March 12, 2014 at 11:28 pm

    what about messages like this

    “Duplicate comment detected; it looks as though you’ve already said that!”

    Reply to this Comment
  22. Victor says

    March 20, 2014 at 1:37 am

    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!

    Reply to this Comment
  23. Josh Weikel says

    March 28, 2014 at 9:24 am

    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.

    Reply to this Comment
  24. shihab says

    May 16, 2014 at 4:37 am

    I used it. It’s work’s fine , thanks a lot.

    Reply to this Comment
  25. Pughalveni says

    June 13, 2014 at 2:14 am

    “The error message mis-align the form boxes.”– I was trying to fix this for the long time.. Thanks a lot for your post .

    Reply to this Comment
  26. Pooja Rathour says

    June 26, 2014 at 12:25 am

    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!

    Reply to this Comment
  27. vinoth says

    August 13, 2014 at 6:04 am

    thank u very much ……i get my result today……..

    Reply to this Comment
  28. Jonathan says

    September 25, 2014 at 1:13 am

    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.

    Reply to this Comment
  29. Anna says

    October 12, 2014 at 9:22 am

    Wow! so simple! thanks a lot!

    Reply to this Comment
  30. Robin Thomas says

    October 24, 2014 at 7:00 am

    Hey …. thanking you …. thank you very much.. You saved my lot of time.

    Reply to this Comment
  31. frans says

    November 17, 2014 at 6:11 pm

    wow, thanks a lot …

    Reply to this Comment
  32. Nimesh says

    January 28, 2015 at 10:45 pm

    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

    Reply to this Comment
    • owem says

      September 19, 2019 at 1:30 am

      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.

  33. Dave Hannon says

    January 29, 2015 at 9:38 am

    @Nimesh: no, I don’t believe that’s possible.

    Reply to this Comment
  34. Nimesh says

    January 29, 2015 at 8:04 pm

    ok no problem, and again thanks for this validation help.

    Reply to this Comment
  35. Dave Hannon says

    February 9, 2015 at 8:25 pm

    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.

    Reply to this Comment
  36. pravin says

    March 18, 2015 at 1:05 am

    Great!,
    thanks.

    Reply to this Comment
  37. Techie says

    April 17, 2015 at 12:30 pm

    Super!!!! Thank you very much

    Reply to this Comment
  38. Eduard says

    April 21, 2015 at 9:32 pm

    Great! so many thanks.

    Reply to this Comment
  39. Neharika says

    June 18, 2015 at 11:30 pm

    Good. Keep it up.

    Reply to this Comment
  40. Renu says

    August 8, 2015 at 7:20 am

    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

    Reply to this Comment
  41. Dave Hannon says

    August 8, 2015 at 9:55 am

    @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
    },

    Reply to this Comment
  42. Halder says

    September 29, 2015 at 3:07 am

    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?

    Reply to this Comment
  43. Dave Hannon says

    September 29, 2015 at 9:50 am

    @Halder – Which browser is it not working on for you? I just tried IE, FireFox, Chrome & Edge and it’s working fine here.

    Reply to this Comment
  44. Debasish Halder says

    October 2, 2015 at 12:18 am

    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”.

    Reply to this Comment
  45. mlll says

    October 9, 2015 at 3:19 pm

    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?

    Reply to this Comment
  46. Dave Hannon says

    October 13, 2015 at 1:54 pm

    @Debasish – why did you change the errorElement? It needs to be a “div” or things will get mis-aligned.

    Reply to this Comment
  47. Dave Hannon says

    October 13, 2015 at 1:55 pm

    @mlll – no, it works in any browser. You probably need to clear your temporary internet files and refresh the page.

    Reply to this Comment
  48. yaicu says

    November 8, 2015 at 10:42 pm

    It is amazing!! Thank you very much…

    Reply to this Comment
  49. janki says

    November 17, 2015 at 2:29 am

    thanks its work for me ! its amazing.

    Reply to this Comment
  50. rose19 says

    December 21, 2015 at 6:33 pm

    and the html…?

    Reply to this Comment
  51. Dave Hannon says

    December 21, 2015 at 6:36 pm

    @rose19 – The entire code needed for this to work is listed at the top of this page.

    Reply to this Comment
  52. rose19 says

    December 21, 2015 at 6:51 pm

    I paste the code at the top of this page into the function.php.. but what i’m writing in my form (html)?

    Reply to this Comment
  53. Dave Hannon says

    December 22, 2015 at 12:03 pm

    @rose19 – You don’t write anything in your form, all this code belongs in your function.php file and css file (for styling).

    Reply to this Comment
  54. Aroon 5 says

    February 10, 2016 at 8:46 pm

    Thanks Dave…it was very helpful..saved me a lot of time… gracias amigo..!!!

    Reply to this Comment
  55. sandeep kamara says

    September 9, 2016 at 3:43 am

    Hello Sir,
    I am very to implement your code and it works in first time. Good Job. Thanks.

    Reply to this Comment
  56. Zed606 says

    February 16, 2017 at 3:47 am

    Great tutorial but one thing what about spaces in comment box and name, it allows to submit but next page error shows up

    Reply to this Comment
    • Dave Hannon says

      February 16, 2017 at 10:06 am

      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

      February 16, 2017 at 10:33 am

      thank you so much for quick response it worked like a charm

    • Dave Hannon says

      February 17, 2017 at 5:45 pm

      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

  57. Violet says

    June 10, 2017 at 5:27 pm

    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!

    Reply to this Comment
    • Violet says

      June 10, 2017 at 6:34 pm

      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

      June 10, 2017 at 6:44 pm

      Can you provide me a link to your blog so I can have a look at what is going on?

  58. Violet says

    June 12, 2017 at 5:39 am

    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.

    Reply to this Comment
    • Dave Hannon says

      June 12, 2017 at 8:34 am

      No problem! You may want to try different a web browser(s) and see if the issue persists.

  59. Selim Reza says

    February 5, 2019 at 12:56 am

    Thank for help.

    Reply to this Comment
  60. Sergio says

    March 8, 2019 at 3:58 am

    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

    Reply to this Comment
    • Dave Hannon says

      March 8, 2019 at 7:54 am

      Thanks for letting me know!

      I’ll update the post with the new URL’s later today.

  61. Max says

    July 2, 2019 at 2:19 am

    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,
    },

    Reply to this Comment
    • Dave Hannon says

      July 2, 2019 at 9:25 am

      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!

  62. owem says

    September 19, 2019 at 1:14 am

    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.

    Reply to this Comment
    • Dave Hannon says

      September 19, 2019 at 9:07 am

      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

      September 19, 2019 at 1:44 pm

      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.

  63. Hefazat says

    August 28, 2023 at 3:54 am

    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.

    Reply to this Comment
    • Dave Hannon says

      August 28, 2023 at 8:08 am

      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?

Leave a Comment
Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • Question2Answer
  • SEO
  • WordPress

Recent Comments

  • Dave Hannon on Comment Form Validation for WordPress
  • Hefazat on Comment Form Validation for WordPress
  • farhan on Question2Answer SEO Meta Tags
  • Dave Hannon on Question2Answer Akismet Plugin
  • mark on Question2Answer Akismet Plugin

Copyright © 2006–2025 Qcybb.com