Improving the WordPress Comments Form with Client-Side Validation
If you use WordPress's HTML5 comments, there's an annoying little gotcha. There's a four year old bug which prevents client-side form validation.
HTML allows <input>
elements to have a required
attribute. In theory, that means the form shouldn't submit until the input is filled in. Sadly, WordPress uses novalidate
on the form - as the name suggests it stops any validation.
But! WordPress is very hackable. Here's how to make a comment form which does client-side validation and as a bonus checks that the commentor's URl starts with http:// or https://
In your theme, there should be a file called comments.php
- that's what we'll be editing.
We're looking for the part which generates the comments form. It will probably be comment_form( $comments_args );
or comment_form();
We're going to need to create a $comments_args
array full of the options we want to set.
The most important is "format" => "xhtml"
- that prevents the dreaded novalidate
from appearing.
PHPif ( comments_open() || pings_open() ) :
$comments_args = array(
// Force client side validation
"format" => "xhtml",
"comment_field" => '<label for="comment">Comment:</label>'.
'<textarea required id="comment" name="comment" cols="45" rows="8" maxlength="65525" placeholder="Write something interesting here…"></textarea>',
'fields' => array(
'author' => '<label for="author">Your Name (required):</label>'.
'<input type="text" required id="author" name="author" value="" size="30" maxlength="245" autocomplete="name" placeholder="Dr. Winston O\'Boogie">',
'email' => '<label for="email">Your Email (required):</label>'.
'<input type="email" required id="email" name="email" placeholder="me@example.com">',
'url' => '<label for="url">Your Website (optional):</label>'.
'<input type="url" id="url" name="url" pattern="^https?:\/\/(.*)" placeholder="https://example.com">'
)
);
comment_form( $comments_args );
Save that and upload it to your theme and - hopefully - it will work. You can test it out by leaving me a comment below.
Mike Nolan says:
But what about my gopher site?!
jailandrade 🚀 says:
@blog great tip
More comments on Mastodon.