【发布时间】:2014-02-28 01:20:21
【问题描述】:
我在表单中使用jqBootstrapValidation plugin 进行客户端验证。我的要求是以下流程:
- 有一个下拉类型
#type,其中custom和other为 类validation-field的选项。 - 我还有两个文本框,
#custom和other,它们没有 上课validation-field。 - 我需要将
custom设为required当值#type是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);
}
【问题讨论】:
标签: jquery validation