为了用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.