BootstrapValidator隐藏后不验证可见字段

时间:2014-08-04 01:40:48

标签: jquery twitter-bootstrap validation

我有一个隐藏某些输入字段的表单,根据特定选择使这些隐藏字段可见。但是,当我希望验证它们时,BootstrapValidator不会验证它们。

我把JSFiddle放在一起; http://jsfiddle.net/FLz6B/1/

我知道为了让BootstrapValidator验证隐藏字段,你需要定义"排除"元素,像这样;

$('#loginform').bootstrapValidator({
    excluded: [":disabled"]
}); 

但是如果我在我的页面上使用它,它将尝试验证隐藏字段,当它们可能不需要验证时。

我还看过BootstrapValidator切换示例,该示例似乎复制了我想要实现的目标,但我还没有能够实现这一目标。 (http://bootstrapvalidator.com/examples/toggle/

任何帮助将不胜感激!谢谢。

1 个答案:

答案 0 :(得分:1)

我自己能解决这个问题。

使用相同的初始调用:

// Exclude disabled fields from validation
$('#loginform').bootstrapValidator({
    excluded: [":disabled"]
}); 

然后我创建了一个强制用户进行选择的选择器:

<select class="form-control" id="type" name="type">
  <option value="" selected disabled>Select Type</option>
  <option value="type1">Type #1</option>
  <option value="type2">Type #2</option>
</select>

在下面,我有一些隐藏的字段取决于选择的类型。

<!-- display and validate always -->
<div id="type1fields">
  <input type="text" name="field1" id="field1">
</div>

<!-- display and validate only if "type2" is selected -->
<div id="type2fields" style="display:none;">
  <input type="text" name="field2" id="field2">
</div>

然后我使用jQuery根据需要将字段设置/取消设置为禁用:

$("#type").on("change", function() {
  var val = $(this).val();

  if(val === "type1") {
    $("#type2fields").fadeOut(); // fade out in case user previously selected it
    $("#field2").attr("disabled", true); // set field to disabled
  }

  if(val === "type2") {
    $("#type2fields").fadeIn();
    $("#field2").attr("disabled", false); // remove the disabled element in case user previously selected it
  }

});
相关问题