Intro

In this short guide, I’ll teach you how to prevent your users from submitting Contact Form 7 in case, the required form fields, were not filled in.
This short snippet of code may be useful, as it improves User Experience. Your visitors, will not accidentally press the button, until are required fields are filled in, thus saving time.

Contact Form 7 Setup

  1. Go to Contact -> Contact Forms and make sure you add an asterisk(*) to all of the required fields, say:
Contact Form 7 required fields

Contact Form 7 required fields

2. Embed your form on the page you want to have it displayed, say via shortcode as such: [contact-form-7 id="0301924" title="Contact form 1"]

3. Use the following snippet of code, to modify the way the submit button works. The following snippet is quite simple:

  • we find the form element (an HTML element with the wpcf7-form class), and we find the submit button, an HTML element with the wpcf7-submit class).
  • we add the disabled attribute to the submit button and we iterate through all of the form elements that have the aria-required, custom data attribute set to true.
  • then, upon interaction with each element, we rerun the code on all required elements, which if not-empty, will disable the disabled attribute from the submit button, thus allowing us to submit the form.

Final Contact Form 7 Result

     

    WP doin dev & security
    WP doin dev & security

    Oh hi there 👋
    It’s nice to meet you.

    Sign up to receive WordPress tips in your inbox, every month.

    I don’t spam! Read my privacy policy for more info.