Skip to content Skip to sidebar Skip to footer

Knockout Validation Not Firing With Knockout Custom Binding

I have a knockout custom binding handler for an input that I need to have validated by knockout-validation. However nothing I've done has worked. Validation is not fired. I can

Solution 1:

Looks like you don't properly update the observable. You could for example use a simple computed to do so:

https://jsfiddle.net/otjg2L8z/2/

I've slightly amended your custom binding:

ko.bindingHandlers.vehiclemileage = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {

        var formattedValue = ko.pureComputed({
            read: function () {
                var text = valueAccessor()();
                return text;
            },
            write: function (newValue) {
                valueAccessor()(newValue);
            }
        });
        ko.utils.registerEventHandler(element, "blur", function (evt) {
            var modelValue = valueAccessor(),
                elementValue = $(element).val();
            if (ko.isWriteableObservable(modelValue)) {
                formattedValue(elementValue);
            }    

            if (evt.timeStamp !== undefined) {
                var fieldName = allBindingsAccessor().fieldName;
                bindingContext.$root.update[fieldName]($(element).val());

            }
        });

        //return true;
    },
    update: function (element, valueAccessor, allBindingsAccessor,     viewModel, bindingContext) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        $(element).val(value);
        //return true;
    }
}

Post a Comment for "Knockout Validation Not Firing With Knockout Custom Binding"