Hamza Ahmad
Hamza Ahmad

Reputation: 545

How to make file upload 'Required' in Contact Form 7?

I have a Contact Form 7 form on my Wordpress website and I have specified that the file upload is mandatory by putting a *, however the users are able to submit the form without file upload.

Relevant Contact Form 7 form is given below:

<div class="filelink">[file* AddanImage filetypes:gif|png|jpg|jpeg]</div>

How do I write the Contact Form 7 code or add a validation perhaps so that the users are not able to submit the form without uploading an image?

Any hints/help/guidance is highly appreciated.

Upvotes: 1

Views: 2755

Answers (1)

Reza Saadati
Reza Saadati

Reputation: 5439

You could use JavaScript to check if the value of a file is existing.

const form = document.querySelector('form'),
      span = document.createElement("span"),
      text = document.createTextNode("Please upload a file: "),
      parent = document.getElementById("file").parentNode,
      file = document.getElementById('file');
      
form.addEventListener('submit', (e) => {
  if (file.value === '') {
    e.preventDefault();
    parent.insertBefore(span, file);
    span.appendChild(text);
  }
});
<form>
  <input type="file" name="file" id="file"><br>
  <input type="submit" value="Upload the file">
</form>

Upvotes: 1

Related Questions