jquery.validate.js校驗select2解決方案 Jquery外掛select2校驗解決方案
為了用jquery.validate.js校驗select2,折騰了2天,現在終於解決了,把方法告訴大家。
一、使用用了select2美化select
Js程式碼- $('select').select2();
二、頁面部分程式碼
Html程式碼- <div class="form-group">
- <label for="tel1" class="control-label">性別:</label>
- <div>
-
<select name="genders" id
- <option value="">請選擇…</option>
- <c:forEach items="${genders}" var="gender">
- <option value="${gender}" ${userInSession.genders eq gender?"selected='selected'":""}>${gender.value}</option>
-
</c:forEach
- </select>
- </div>
- </div>
三、使用jquery.validate.js
匯入js檔案
jquery.validate.min.js
additional-methods.min.js
messages_zh.min.js
additional-methods-custom.js (自己定義的校驗方法擴充套件js檔案)
四、校驗
Js程式碼- var validateObj = $('#userInfoEditForm').validate({
-
ignore: ""
- errorClass : 'help-block',
- focusInvalid : true,
- rules : {
- genders : {
- required : true
- }
- },
- messages : {
- genders : {
- required : "請選擇性別"
- }
- submitHandler : function(form) {
- return false;
- form.submit();//form.submit(); 或者$(form).ajaxSubmit();
- }
- });
- $("#genders").change(function(){
- $(this).valid();
- });
五、問題說明
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程式碼- $("#genders").change(function(){
- $(this).valid();
- });
需要注意的是: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.