Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

javascript - How can I apply this validation function to all inputs?

I have this code that works to validate just one input file, but I need to validate multiple fields (since the users can add as much "input files" as they want) and don't now how. I've being trying to use loops but with no results (mostly because I don't understand them even when I've been reading it over and over in w3school).

https://jsfiddle.net/ElenaMcDowell/2xrqp6zg/2/

$( ".postreplyForm" ).submit(function( event ) {
var fileBox = $('.post-file').val(); //This is the Class of the input file
if (fileBox === '') {
   //If there is no file
   return;
} else {
   //File format
   var fileExtension = ['jpg', 'jpeg', 'png', 'mp3', 'mp4', 'pdf', 'pps', 'ppt', 'pptx', 'xls', 'doc', 'docx', 'txt'];
   if ($.inArray($('.post-file').val().split('.').pop().toLowerCase(), fileExtension) == -1) {
      $(".errorFile").html('<br><center><p class="signuperror">File format not allowed.</p></center><br>');
   } else {
      $(".errorFile").html(' ');
      //File size
      var fileSize = $('.post-file')[0].files[0].size;
      if (fileSize > 1000000) {
         $(".errorFile").html('<br><center><p class="signuperror">The file is too big.</p></center><br>');
      } else {
         $(".errorFile").html(' ');
         return;
      }

   }

}
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can get all values using $('.post-file')[0].files then loop through each files and check condition then print some message in your div errorFiles . Also , use some variable and set it to true and if any condition doesn't meet set to false depending on this variable prevent your form to submit.

Demo Code :

$(".postreplyForm").submit(function(event) {
  var fileBox = $('.post-file').val();
  if (fileBox === '') {
    return false; //prevent form to submit
  } else {
    //File format
    var fileExtension = ['jpg', 'jpeg', 'png', 'mp3', 'mp4', 'pdf', 'pps', 'ppt', 'pptx', 'xls', 'doc', 'docx', 'txt'];
    var flag = true; //decalre this
    var fileArray = $('.post-file')[0].files; //get all files
    $(".errorFile").html('');
    //loop through files
    $.each(fileArray, function(i, v) {
      name = v.name; //name of file
      fileSize = v.size; //size of file
      console.log(name);
      if ($.inArray(name.split('.').pop().toLowerCase(), fileExtension) == -1) {
        flag = false;
        $(".errorFile").html('<br><center><p class="signuperror">File format not allowed.</p></center><br>');
      } else {
        if (fileSize > 1000000) {
          $(".errorFile").html('<br><center><p class="signuperror">The file is too big.</p></center><br>');
          flag = false;
        }
      }
    })
  }
  //check not true prevnt submit
  if (!flag) {
    return false;
  } else {
    return true;
  }

});
.errorFile {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="create-mode postreplyForm" method="post" action="a.php" name="post" enctype="multipart/form-data">
  <table class="table-newpost">
    <tr>
      <td colspan="5"><br>
        <div style="font-weight: bold; font-size: 14px; margin-bottom: -10px;">Attach file</div>
        <br>
        <span>File formats allowed: (.jpg, .jpeg, .png, .mp3, .mp4, .pdf, .zip, .rar, .pps, .ppt, .pptx, .xls, .doc, .docx, .txt, .rtf)</span>
        <br><br>
        <div class="fileBox">
          <div style="display: flex; margin-bottom: 2px;">
            <input type="file" name="file[]" id="fileID1" class="post-file" multiple="multiple">
            <div id="1" class="fileBtn fileDeleteInPost" title="Delete file">x</div>
            <div class="fileBtn add-file" title="Add file">+</div>
          </div>
        </div>
        <div class="errorFile"></div>
      </td>
    </tr>
    <tr>
      <td colspan="5" style="text-align: right;">
        <input type="hidden" name="reply-by" value="<?php echo $_SESSION['userId']; ?>">
        <button type="submit" name="submit-postreply" id="Miau">Submit</button>
      </td>
    </tr>
  </table>
</form>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...