I am using knockout.js with validation and jquery placeholder plugin for ie8. Knockout binding:
ko.bindingHandlers.placeholder = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
ko.applyBindingsToNode(element, { attr: { placeholder: valueAccessor() } });
$(element).placeholder();
$(element).focus();
$(element).blur();
}
}
usage:
<div>
<input type="text" data-bind="placeholder: 'Product name...', value: productName, valueUpdate: 'afterkeydown'" />
<span data-bind="visible: productName.isValid" class="validationMessageValid">Ok.</span>
<span data-bind="validationMessage: productName" class="validationMessage"></span>
</div>
in viewModel:
...
self.productName = ko.observable('').extend({ required: { params: true, message: 'Name of the product cannot be empty.' } });
...
Here is the problem. When text input is cleared plugin is setting placeholder value. Knockout validation reads this value instead of empty string, so that validation is not working properly, it says 'OK' because of the placeholder value.
After text from input is removed there are two validation checks, first with empty string, second with placeholder string. What's interesting in case of textarea element there is only the first one and everything works fine.
My idea is to check if value is the same as placeholder, if it is then forward empty string into validation.
Knockout validation plugin already overrides default 'value' binding and sends valueAccessor to another binding called 'validationCore', what I would like to do is to insert this one condition into valueAccessor.
Maybe there is a simpler solution? Appreciate any ideas.
knockout.js 2.3, jquery 1.10.2, placeholder plugin 2.0.7