是否可以在 HTML5 中驗證 input=file 的大小和型別?


是的,可以驗證 input type = “file”的大小和型別。可以使用 jQuery 來獲得期望的結果 −

<!DOCTYPE html>
<html>
<head>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
   <body>
      <form >
         <input type="file" id="myfile" data-max-size="32154" />
         <input type="submit"/>
      </form>
      <script>
         $(function(){
            $('form').submit(function(){
               var val = true;
                  $('input[type=file][data-max-size]').each(function(){
                     if(typeof this.files[0] !== 'undefined'){
                        var max = parseInt($(this).attr('max-size'),10),
                        mySize = this.files[0].size;
                        val = max > mySize;
                        return val;
                     }
                  });
                  return val;
               });
            });
      </script>
   </body>
</html>

更新於: 2020 年 6 月 25 日

269 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.