Learn how to do form validation with javascript in WordPress.
We will do form validation with javascript which will prevent the comment form from submitting if required fields are missing and show proper validation message. Submitting the comment form with empty fields in WordPress shows an error which is bad user experience.
Implementation
- We will use JQuery validate to handle the validation.
- We will create a
functionand append thescriptto thefooterin wordpress.
jQuery(document).ready(function($) {
$('#commentform').validate({
rules: {
author: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
comment: {
required: true,
minlength: 20
}
},
messages: {
author: "Please provide a name",
email: "Please enter a valid email address.",
comment: "Please fill the required field"
},
errorElement: "div",
errorPlacement: function(error, element) {
element.after(error);
}
});
});
Explanation
- We set
rulesfor the fields. Properites are added using fields nameauthor : {required: true}. Learn more about it here. - Then we set the error
messagesusing the fields name. - After this we select the element in which the error message will be displayed,
divin this case. - And then we set where the error should be placed.
Now we need to wrap this inside a function.
/*Comment Validation*/
function comment_validation_init() {
if(is_single() && comments_open() ) { ?>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#commentform').validate({
rules: {
author: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
comment: {
required: true,
minlength: 20
}
},
messages: {
author: "Please provide a name",
email: "Please enter a valid email address.",
comment: "Please fill the required field"
},
errorElement: "div",
errorPlacement: function(error, element) {
element.after(error);
}
});
});
</script>
<?php
}
}
add_action('wp_footer', 'comment_validation_init');
Explanation
- We will check if the current page is single page and comments are open on this page with
is_single() && comments_open()which are inbuilt functions of wordpress. - Then we import JQuery validate script with CDN.
- And in the end we hook this function to
footerusingadd_action('wp_footer', 'comment_validation_init');. It basically executes the current functioncomment_validation_initinside the given functionwp_footer.