jquery-plugins – 使用Jquery Validate插件验证bootstrap-select

前端之家收集整理的这篇文章主要介绍了jquery-plugins – 使用Jquery Validate插件验证bootstrap-select前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正面临着使用jquery validate plugin验证select使用bootstrap-select.js插件进行美化的问题. bootstrap-select.js期待类selectpicker并遵循一行代码
  1. $('.selectpicker').selectpicker();

用于美化选择html.

但是,它使用jquery validate插件导致验证问题.除非并且直到类selectpicker未被删除,否则select in not at all validated.删除类后,将正确执行验证.
以下是我的选择html:

  1. <select class="input-medium required" id="editCategory_sltCategoryName"
  2. name="editCategory_sltCategoryName">
  3. <option value="">
  4. Select Category
  5. </option>
  6. <option>
  7. Reusable Components
  8. </option>
  9. <option>
  10. BU Connects
  11. </option>
  12. </select>

以下是js:

  1. $('#frm_editCategory').validate({
  2. rules: {
  3. editCategory_sltbuName: {
  4. required: true
  5. },editCategory_sltCategoryName: {
  6. required: true
  7. },editCategory_categoryName: {
  8. minlength: 2,required: true,buname: true
  9. },editCategory_categoryDescription: {
  10. minlength: 2,buname: true
  11. }
  12. },highlight: function(element) {
  13. $(element).closest('.control-group')
  14. .removeClass('success').addClass('error');
  15. },success: function(element) {
  16. element.text('OK!').addClass('valid')
  17. .closest('.control-group')
  18. .removeClass('error').addClass('success');
  19. },submitHandler: function(event) {
  20. return true;
  21. }
  22. });

我试图通过为它编写自定义方法来做到这一点,但它是没有用的.

解决方法

我会尽力根据你所描述的内容回答你的问题,因为我相信我遇到了类似的问题,并且能够解决它.

首先,我假设您使用selectpicker()方法正确初始化了您的选择.上面,你写道

  1. $('.selectpicker').selectpicker();

但是你没有任何带有类selectpicker的select元素,所以我认为你的意思是

  1. $('select').selectpicker();

当您调用selectpicker()时,Bootstrap将在您的select元素后插入其他元素(div,button,span,ul和li).但请注意,Bootstrap将隐藏()原始的select元素.因为您的select是隐藏的,所以JQuery Validate将在提交表单时忽略它的验证.这是主要问题.

要告诉Jquery Validate不要忽略隐藏的选择输入,您可以执行以下操作…

  1. // Initialize form validation rules,submit handler,etc.
  2. $('#frm_editCategory').validate({
  3. .
  4. .
  5. .
  6. });
  7.  
  8. // The default value for $('#frm_editCategory').validate().settings.ignore
  9. // is ':hidden'. Log this to the console to verify:
  10. console.log($('#frm_editCategory').validate().settings.ignore);
  11.  
  12. // Set validator to NOT ignore hidden selects
  13. $('#frm_editCategory').validate().settings.ignore =
  14. ':not(select:hidden,input:visible,textarea:visible)';

为什么还需要包含输入:visible和textarea:visible?之前,设置是忽略所有隐藏的输入.如果您只忽略:not(select:hidden),您将忽略任何不是隐藏选择的输入.但这太宽松了,因为可见输入[type = text]不是隐藏选择.所以,它也会被忽略.我们想要的是忽略任何元素:

  1. - is *not* a hidden `select`
  2. - *is* a hidden `input`
  3. - *is* a hidden `textarea`

要将这一切都安装到:not selector中,您要忽略以下任何元素:

  1. - is *not* a hidden `select`
  2. - is *not* a visible `input`
  3. - is *not* a visible `textarea`

因此…

  1. $('#frm_editCategory').validate().settings.ignore =
  2. ':not(select:hidden,textarea:visible)';

猜你在找的jQuery相关文章