Notification if Comment Author Field is left empty. E.g. change input border colour

I am having a comment section on my website. The author comment field is required. Any idea how to display a notification for a user if author field is left empty after submitting the comment? Something else than wp_die ?

What I would like to have is for example: change comment field border colour to red and say: 'please, write a name.'

Answers 1

  • You can do this using jQuery.

    First of all, you need to add your script into your functions.php

    function my_theme_scripts() {
    wp_enqueue_script( 'my-great-script', get_site_url() . '/js/my-great-script.js', array( 'jquery' ), '1.0.0', true );
    add_action( 'wp_enqueue_scripts', 'my_theme_scripts' );

    Then, in your file (my-great-script.js), you will have to have something like this:

    jQuery( ".form-submit" ).click(function(event) {
        if( !jQuery("input[name='author']").val() ) {
              jQuery("#author").css({"border-color": "red", "border-style": "solid", "border-width": "5px"});

    form-submit is the class of the submit button, so when a user clicks it, we will check using jQuery if the author field is empty (!jQuery("input[name='author']").val()), next line is there to stop the submit button from triggering, and finally we change the CSS of the author field in order to highlight it red.

    You also mentioned about a message saying "Please write a name", I didn't cover that but you get the idea, you could easily create a div element with that message, keep it hidden and then show it along with the red border using jQuery again.

    I did a live example in one of my test servers if you want to check, just click on Post Comment without filling any author name.

Related Questions