Why does `add_theme_support( 'html5', array( 'comment-form' )` disable client side validation?

In order to use HTML5 markup for the comment forms, I add the following code snippet to functions.php:

add_theme_support( 'html5', array( 'comment-form' ) );

However, it disables client side validation on form submit and I get redirected to an error page:

Now, if I remove add_theme_support( 'html5', array( 'comment-form' ) ); and submit the comment form, I get client side validation:

Can anybody explain why this is? Is it a bug? Or expected behavior?

I am currently using WordPress 4.7.

Topic add-theme-support comment-form html5 Wordpress

Category Web


You can remove novalidate attribute with this simple Javascript:

<script type="text/javascript">
    var commentForm = document.getElementById('commentform'); 
    commentForm.removeAttribute('novalidate');
</script>

No jQuery needed.

You can include the following code to run script just on posts:

footer.php

<?php if( is_singular() ) : ?>
    <script type="text/javascript">
        var commentForm = document.getElementById('commentform');
        commentForm.removeAttribute('novalidate');
    </script>
<?php endif; ?>

No, it is not a bug. This is how core handles it. If you look into /wp-includes/comment-template.php, you'll notice, that the only difference in <form> element, is novalidate attribute added, when current_theme_supports( 'html5', 'comment-form' ) is true. But there are other html elements within comment form, which are affected by theme's choice of html5 support. For example: input field for email ( type="email" - html5, type="text" - xhtml ), and input field for url ( type="url" - html5, type="text" - xhtml ).

I would not recommend to remove theme support for html5. WordPress, now, builds our documents with <!DOCTYPE html>, which means, HTML5. If we do remove support, our document will not validate as correct XTML5.

So, how to deal with this offending novalidate attribute? Simple jQuery script will fix it.

Create file removenovalidate.js and put the code below in it:

jQuery( document ).ready(function($) {
    $('#commentform').removeAttr('novalidate');
});

Save this file to your theme's folder. Add the code below to your theme's functions.php:

function fpw_enqueue_scripts() {
    if ( is_single() ) { 
        wp_register_script( 'fpw_remove_novalidate', get_stylesheet_directory_uri() . '/removenovalidate.js', array( 'jquery' ), false, true );
        wp_enqueue_script( 'fpw_remove_novalidate' );
    }
}
add_action('wp_enqueue_scripts', 'fpw_enqueue_scripts', 10 );

All done. Your comments form will validate now.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.