Monthly Archives: December 2016

Knockout Binding Handler: validationPopover

<script type="text/javascript">
    ko.bindingHandlers.validationPopover = {
        init: function (element, valueAccessor, allBindings) {
            if (!allBindings.has("value")) {
                return;
            }
            var $element = $(element);
            var value = allBindings.get("value");
            $element.popover($.extend({}, ko.unwrap(valueAccessor()), {
                content: function () {
                    return value.error();
                },
                trigger: "manual"
            }));
            value.subscribe(function () {
                $element.popover(value.isValid() ? "hide" : "show");
            });
        }
    };
</script>

<input type="text" data-bind="value: name, validationPopover: {}" />

<script type="text/javascript">
    ko.validation.init({
        insertMessages: false
    });
    
    function ViewModel() {
        var self = this;
        self.name = ko.observable().extend({ required: true });
    }
    
    ko.applyBindings(new ViewModel());
</script>