jQuery Validate驗證上傳檔案大小

admin發表於2019-01-14
本章節分享一段程式碼例項,它實現了驗證上傳檔案大小的功能。

Validate外掛並沒有自帶這樣的功能,所以規則需要我們自定義。

驗證上傳檔案的型別功能Validate也沒有提供,具體可以參閱jQuery Validate限定上傳檔案型別一章節。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
ul li{
  list-style:none;
  margin-top:5px;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script src="http://www.softwhy.com/demo/jQuery/js/jquery.validate.js"></script>
<script src="http://www.softwhy.com/demo/jQuery/js/messages_zh.js"></script>
<script>
jQuery.validator.addMethod("checkSize", function (value, element, param) {
  var fileSize = element.files[0].size;
  if (fileSize > param) {
    return false;
  } else {
    return true;
  }
}, "請上傳大小在1M一下的檔案");
  
$(document).ready(function () {
  $("#one").validate({
    rules: {
      age: {
        required: true,
        range:[18,40]
      },
      num: {
        required: true,
        min: 12
      },
      file: {
        required: true,
        checkSize: 1 * 1024 * 1024
      }
    },
    messages: {
      age: {
        required: "年齡必須填寫",
        range: "年齡必須介於18-40之間"
      },
      num: {
        required: "數目為必填",
        min: "數目最少為12"
      },
      file: {
        required: "必須檔案",
      }
    }
  });
});
</script>
</head>
<body>
<form id="one"action="http://www.softwhy.com/">
  <ul>
    <li>年齡:<input type="text" name="age"/></li>
    <li>數目:<input type="text" name="num" /></li>
    <li>檔案:<input type="file"  name="file"/></li>
    <li>
      <input type="submit" value="提交"/>
      <input type="reset" value="重置"/>
    </li>
  </ul>
</form>
</body>
</html>

實現限定上傳檔案大小在1M之內,更多內容可以參閱jQuery Validate的addMethod()一章節。

相關文章