AdSense

網頁

2018/2/1

在jQuery Validation 加入自訂規則

在jQuery Validation套件加入自訂規則(custom rules)的方法如下。

使用jQuery.validator.addMethod()加入自訂規則,例如下面範例加入自訂規則noSpace

<div>
  <form id="yourForm">
    輸入地址:<input name="address" type="text"/>
    <br>
    <button type="button" id="confirm-button">確認</button>
  </form>
</div>

<script>
$(document).ready(function(){

  // 在jQuery Validation中加入自訂的noSpace規則
  jQuery.validator.addMethod("noSpace", function(value, element) { 
    if(value) {
      return value.match(/\s+/g) == null; // 輸入內容中不可有空白字元
    } else {
      return false;
    }
  }, "不可輸入空白");
  
  // 設定表單的驗證規格
  var validator = $('#yourForm').validate({
    rules: {
      address: "noSpace" // 設定address輸入欄位的規則為noSpace
    }
  });
  
  // 當按下[確認]按鈕時進行表單欄位驗證
  $('#confirm-button').click(function() {
    if(validator.form()) {
      $('#yourForm').submit();
    }
  }); 

});
</script>

如果覺得文章有幫助的話還幫忙點個Google廣告,感恩。


參考:

沒有留言:

AdSense