我在表单中使用jqBootstrapValidation plugin进行客户端验证。我的要求如下:
#type
,其中包含custom
和other
类validation-field
的选项。#custom
和other
,它们都没有
有班级validation-field
。custom
时required
#type
的{{1}}为custom
,需要other
作为required
#type
的值为other
。所以我将课程validation-field
添加到
字段(包括它用于验证)和删除
来自验证不需要的字段的validation-field
。问题:
向验证函数添加字段的方法是再次调用函数init_validation
,但删除字段(即)将下拉列表从other
更改为custom
后,不应验证#other
文本框。但它验证了'#other'和'#format'
HTML:
<form method="post" action="" class="form-horizontal" role="form" novalidate="novalidate">
<div class="form-group">
<label class="col-sm-2 control-label required" for="type">Type</label>
<div class="col-sm-5">
<select id="type" name="type" class="form-control validation-field">
<option value="single">Single</option>
<option value="multiple">Multiple</option>
<option value="other">Other</option>
<option value="custom">Custom</option>
</select>
</div>
<span class="help-block">
</span>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="other">Other</label>
<div class="col-sm-5">
<input type="text" id="other" name="other" class="form-control" required="required" data-validation-required-message="This field is required if type is Other" />
</div>
<span class="help-block">
</span>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="custom">Custom</label>
<div class="col-sm-5">
<input type="text" id="custom" name="custom" class="form-control" required="required" data-validation-required-message="This field is required if type is Custom" />
</div>
<span class="help-block">
</span>
</div>
<div class="form-group">
<div class="col-sm-2"></div>
<div class="col-sm-5">
<button type="submit" id="submit" name="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
使用Javascript:
$(document).ready(function(){
//Init Validation
init_validation();
//On Selecting Field Type
$("#type").change(function(){
switch ($(this).val()) {
case "custom":
element_required="#custom";
element_not_required="#other";
break;
case "other":
element_required="#other";
element_not_required="#custom";
break;
default:
element_required="";
element_not_required="#other"+","+"#custom";
break;
}
$(element_required).addClass("validation-field");
$(element_not_required).removeClass("validation-field");
$(element_not_required).closest(".form-group").removeClass("has-error");
$(element_not_required).closest(".form-group").find(".help-block").html("");
jqvalidation=undefined;
init_validation();
});
});
function init_validation() {
var jqvalidation=$(".validation-field").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
alert("Error");
},
submitSuccess: function($form, event) {
alert("Success");
}
});
console.log(jqvalidation);
}
答案 0 :(得分:2)
经过几天的努力,终于找到了解决方案。这可能有助于重新启动验证过程的其他人。
替换
jqvalidation=undefined;
通过
$("input,select,textarea").jqBootstrapValidation("destroy");
更新了小提琴:http://jsfiddle.net/3hczf/4/