Knockout验证插件是否有任何选项可以将错误类应用于错误输入的父级或父级?如果没有,任何人都可以提出修改敲除验证的方法吗?
请参阅以下小提琴,了解我正在努力实现的目标。开箱即用的敲除验证设置输入的类,但我希望它改为设置包含控件组的类:
查看
<p>Clear the field and tab out of it to "see" the current behaviour - error class is added directly to the input by knockout validation. But I want to add class "error" to control-group containing the input instead of directly to the input.</p>
<div class="form-horizontal">
<div class="control-group">
<label class="control-label">Field</label>
<div class="controls">
<input type="text" data-bind="value: testField" class="">
</div>
</div>
<button data-bind="click: setErrorOnControlGroup">Click to see desired effect</button>
</div>
的Javascript
ko.validation.configure({
registerExtenders: true,
messagesOnModified: true,
decorateElement: true,
errorClass: 'error',
insertMessages: false,
parseInputAttributes: true,
messageTemplate: null
});
var viewModel = {
testField: ko.observable("123").extend({required: true}),
setErrorOnControlGroup: function() {
$("input.error").removeClass("error");
$(".control-group").addClass("error");
}
};
ko.applyBindings(viewModel);
样式表(仅限说明 - 我不应该这样,因为我想使用twitter bootstrap样式)
/*NOTE: This is not actually the style I want, it just illustrates the default behaviour of knockout validation*/
input.error {
background-color: #aaffaa;
}
我问,因为我使用的是Twitter引导样式,它使用输入的父控件组元素来设置“错误”输入的样式。
答案 0 :(得分:3)
我调整互斥量的小提琴以达到效果。 http://jsfiddle.net/3vGVC/9/。虽然有改进的余地,但也许可以指定要应用的css类。这是bindingHandler,可以应用于容器。
ko.bindingHandlers.validationElement = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var valueIsValid = valueAccessor().isValid();
if(!valueIsValid) {
$(element).addClass("error");
}
else {
$(element).removeClass("error");
}
}
}
答案 1 :(得分:2)
您可以编写自己的绑定。
看看敲门验证源中validationElement
绑定的来源。