Does the Knockout validation plugin have any option to apply the error class to the parent or parent's-parent of the input in error? If not can anybody suggest an approach to modify knockout validation to do this?
Please see the following fiddle for an example of what I'm trying to achieve. Out of the box knockout validation sets the class of the input, but I want it to instead set the class of the containing control-group:
http://jsfiddle.net/fbA4m/1/
View
<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);
Stylesheet (Illustrative only - I shouldn't need this because I want to the use the twitter bootstrap styles)
/*NOTE: This is not actually the style I want, it just illustrates the default behaviour of knockout validation*/
input.error {
background-color: #aaffaa;
}
I ask because I'm using twitter bootstrap styling and it uses the input's parent control-group element to style "error" inputs.
I tweaked mutex's fiddle to achieve the effect. http://jsfiddle.net/3vGVC/9/. There's room for improvement though, perhaps so that one could specify the css class to apply. Here's the bindingHandler, which can be applied to the container.
ko.bindingHandlers.validationElement = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var valueIsValid = valueAccessor().isValid();
if(!valueIsValid) {
$(element).addClass("error");
}
else {
$(element).removeClass("error");
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With