1. 程式人生 > >jquery.validate.js校驗select2解決方案 Jquery外掛select2校驗解決方案

jquery.validate.js校驗select2解決方案 Jquery外掛select2校驗解決方案

為了用jquery.validate.js校驗select2,折騰了2天,現在終於解決了,把方法告訴大家。

一、使用用了select2美化select

Js程式碼  收藏程式碼
  1. $('select').select2();  

二、頁面部分程式碼

Html程式碼  收藏程式碼
  1. <div class="form-group">  
  2.   <label for="tel1" class="control-label">性別:</label>  
  3.     <div>  
  4.       <select name="genders" id
    ="genders" class="form-control">  
  5.         <option value="">請選擇…</option>  
  6.         <c:forEach items="${genders}" var="gender">  
  7.         <option value="${gender}" ${userInSession.genders eq gender?"selected='selected'":""}>${gender.value}</option>  
  8.        </c:forEach
    >  
  9.      </select>  
  10.   </div>  
  11. </div>  

三、使用jquery.validate.js

匯入js檔案

jquery.validate.min.js

additional-methods.min.js

messages_zh.min.js

additional-methods-custom.js  (自己定義的校驗方法擴充套件js檔案)

四、校驗

Js程式碼  收藏程式碼
  1. var validateObj = $('#userInfoEditForm').validate({  
  2.     ignore: ""
    ,  
  3.     errorClass : 'help-block',    
  4.     focusInvalid : true,  
  5.     rules : {    
  6.         genders : {  
  7.             required : true  
  8.         }  
  9.     },    
  10.     messages : {    
  11.         genders : {    
  12.             required : "請選擇性別"    
  13.         }  
  14.     submitHandler : function(form) {  
  15.         return false;  
  16.         form.submit();//form.submit(); 或者$(form).ajaxSubmit();  
  17.     }    
  18. });   
  19. $("#genders").change(function(){  
  20.     $(this).valid();  
  21. });  

五、問題說明

1、使用select2美化select下拉列表後,select2會把原來的select隱藏掉,設定css屬性(display:none),然後再通過select2重新定製介面

2、但jquery.validate.js預設不是校驗:hidden屬性的控制元件,所以造成原來的select校驗不了

官網說明:

ignore (default: ":hidden")

Type: Selector

Elements to ignore when validating, simply filtering them out. jQuery's not-method is used, therefore everything that is accepted by not() can be passed as this option. Inputs of type submit and reset are always ignored, so are disabled elements.

Example: Ignores all elements with the class "ignore" when validating.

$("#myform").validate({

  ignore: ".ignore"

});

3、解決方法就是加ignore屬性,把值設定為""空字串

ignore: "",

4、設定ignore後在提交時就會對隱藏的屬性進行校驗,但選擇的時候沒有進行實時校驗,因為你選擇的是select2。所以要給select加一個change事件,當改變時,再校驗一次。

Js程式碼  收藏程式碼
  1. $("#genders").change(function(){  
  2.     $(this).valid();  
  3. });  

 需要注意的是:valid方法是jquery.validate.js中的方法,所以用的時候,要先呼叫初始化方法validate( ),

然後在後面再重新呼叫valid()校驗方法。

valid( )  可以校驗整個表單,也可以校驗單個屬性。

官網說明:

valid( )  

Returns: Boolean

Description: Checks whether the selected form is valid or whether all selected elements are valid.

validate() needs to be called on the form before checking it using this method.