ko_md_validation

Knockout validation extender in master-detail scenario

HTML

<div>
    <ul class="list" data-bind="foreach: tables">
        <li><a data-bind="text: name, click: $parent.selectTable"></a></li>
    </ul>
</div>
<div>
    <div id="editor-content">
        <section id="viewNameSection">
            <div data-bind="with: selectedTable">
                <label>View name: </label>
                <input id="txtViewName" data-bind="value: viewName, valueUpdate: 'input'" placeholder="eg. MyView" />
                <span style="color: red;" data-bind="visible: viewName.hasError, text: viewName.validationMessage"></span>
            </div>
        </section>
    </div>
</div>

JavaScript

var t;
var schema;

ko.extenders.myrequired = function (target, overrideMessage) {
    //add some sub-observables to our observable
    target.hasError = ko.observable();
    target.validationMessage = ko.observable();

    //define a function to do validation
    function validate(newValue) {
        target.hasError(newValue ? false : true);
        target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
    }

    //initial validation
    //validate(target());

    //validate whenever the value changes
    target.subscribe(validate);

    //return the original observable
    return target;
};

function PluginViewModel() {
    var self = this;

    self.name = ko.observable();
    self.code = ko.observable();
};

function item() {
    var self = this;

    self.id = ko.observable();
    self.listIndex = ko.observable();
    self.value = ko.observable();
    self.label = ko.observable();
    self.tabPos = ko.observable();
    self.plugins = ko.observableArray();
};

function TableViewModel() {
    var self = this;

    self.id = ko.observable();
    self.name = ko.observable();
    self.viewName = ko.observable().extend({ myrequired: "Please enter a view name" });
    self.columns = ko.observableArray();
    self.filteredColumns = ko.observableArray();
};

function SchemaViewModel() {
    var self = this;

    self.name = ko.observable();
    self.tables = ko.observableArray();

    // Table selected in left panel
    self.selectedTable = ko.observable();
    self.selectTable = function (p) {
        self.selectedTable(p);
    }
};


    schema = new SchemaViewModel();
    t = new TableViewModel();
    
    t.name("foo");
    schema.tables.push(t);
    
    ko.applyBindings(schema);