首页 > Web开发 > 详细

jquery.validate.js校验select2解决方案,Jquery插件select2校验解决方案

时间:2015-09-16 02:17:34      阅读:436      评论:0      收藏:0      [点我收藏+]

jquery.validate.js校验select2解决方案

Jquery插件select2校验解决方案

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

蕃薯耀 2015年9月15日 11:25:26 星期二

http://fanshuyao.iteye.com/

?

为了用jquery.validate.js校验select2,折腾了2天,现在终于解决了,把方法告诉大家。

?

一、使用用了select2美化select

?

?

$(‘select‘).select2();

?

?

?

二、页面部分代码

?

?

<div class="form-group">
  <label for="tel1" class="control-label">性别:</label>
    <div>
      <select name="genders" id="genders" class="form-control">
        <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文件)

?

四、校验

?

?

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事件,当改变时,再校验一次。

?

$("#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.?

?

?

?

?

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

蕃薯耀 2015年9月15日 11:25:26 星期二

http://fanshuyao.iteye.com/

jquery.validate.js校验select2解决方案,Jquery插件select2校验解决方案

原文:http://fanshuyao.iteye.com/blog/2243544

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!