skip to Main Content

I have this code in my child theme template submit_video.php. I want to validate that the subscriber has uploaded a thumbnail or they CANNOT publish a video. Here is the code used for upload..I have tried several things already. I am just a beginner in JS..This is the code to Upload a thumbnail..I just cant figure out how to validate this now, with JS or other code per se’ (PHP)

<!--UploadThumbnail-->
<div class="col-12 mb-2">
    <label class="label-sm qs-font-weight-medium bm_cya_form_label">
    <?php esc_html_e('Upload Thumbnail', 'betube') ?> :
    <span class="text-danger">*</span>
    <span class="small"><?php esc_html_e('Best image size is 850x550px', 'betube') ?></span>
    </label>
    <input class="form-control form-control-lg" type="file" name="upload_attachment[]" id="btp_thumbnail" accept="image/*">
    </div>
    <!--UploadThumbnail-->

Any help would be appreciated..Thanks in Advance!

I tried this generic code changing names etc. No go and couldn’t figure it out

function validateForm() {
  var x = document.forms["myForm"]["fname"].value;
  if (x == "") {
    alert("Name must be filled out");
    return false;
  }
} 

2

Answers


  1. your input selector is wrong, using document.forms requires the name attribute of the element, so your selector code should be, assuming the input with id=btp_thumbnail contains the thumbnail

    var x=document.forms['myForm']['upload_attachment[]'];
    

    mdn:Document: forms property

    Login or Signup to reply.
  2. You don’t need a function for validating the input file element. Just set the attribute required on the element. THe form will only submit if it is valid meaning that all required form fields in the form are valid.

    About the naming. In a form you should always have a name attribute on each form field and the form itself. You can either use the dot syntax (document.forms.uploadthumbnail) or the "array" syntax (document.forms['uploadthumbnail']). In the case of the file input with the name upload_attachment[] you need to use the array syntax because of the square brackets in the name: document.forms.uploadthumbnail['upload_attachment[]'].

    document.uploadthumbnail.addEventListener('submit', e => {
      e.preventDefault();
      let form = e.target;
      console.log('You are uploading',form['upload_attachment[]'].files.length, 'file');
    });
    <form name="uploadthumbnail">
      <!--UploadThumbnail-->
      <div class="col-12 mb-2">
        <label class="label-sm qs-font-weight-medium bm_cya_form_label">Upload Thumbnail<span class="text-danger">*</span> 
          <input class="form-control form-control-lg" type="file" name="upload_attachment[]" accept="image/*" required>
        </label>
      </div>
      <!--UploadThumbnail-->
      <button>Submit</button>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search