jQuery Validate的format()用法

admin發表於2018-08-05
此為字串格式化方法,如果會C#等語言,那麼非常好理解,不會關係也不大。

先看一個程式碼片段:

[JavaScript] 純文字檢視 複製程式碼
rangelength: $.validator.format("請輸入長度在 {0} 到 {1} 之間的字串")

很明顯輸入字串的長度被rangelength規範限定在m-n範圍,一個規範對應著一個方法,為這個方法傳遞的引數會和format方法中的{n}依次對應,看如下程式碼片段:

[JavaScript] 純文字檢視 複製程式碼
pw: {
  required: true,
  rangelength: [5, 15]
}

雖然是傳遞了一個陣列,其實在方法內部將其分解為兩個引數,分別是5和15。

{0}將會被5替代,{1}將會被15替代,以此類推。

總結:format方法引數字串中的指定格式字串片段(如{0}),將會依次被傳遞的引數替代。

程式碼例項如下:

[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>
$(document).ready(function () {
  $("#one").validate({
    rules: {
      username: {
        required: true,
        maxlength: 20
      },
      pw: {
        required: true,
        rangelength: [5, 15]
      },
      address: {
        required: true,
        minlength: 15
      }
    },
    messages: {
      username: {
        required: "使用者名稱是必填專案",
        maxlength: $.validator.format("使用者名稱長度不得超過 {0}")
      },
      pw: {
        required: "密碼是必填專案",
        rangelength: $.validator.format("密碼的長度必須在 {0} - {1} 之間")
      },
      address: {
        required: "地址是必填專案",
        minlength: $.validator.format("地址描述長度不得少於 {0}")
      }
    }
  });
});
</script>
</head>
<body>
<form id="one"action="http://www.softwhy.com/">
  <ul>
    <li>姓名:<input type="text" name="username"/></li>
    <li>密碼:<input type="password" name="pw"/></li>
    <li>住址:<input type="text" name="address"/></li>
    <li>
      <input type="submit" value="提交"/>
      <input type="reset" value="重置"/>
    </li>
  </ul>
  <label for="username"></label>
</form>
</body>
</html>

相關文章