2
votes

I have a dropdown loaded using knockout and i have used subscribe event to handle change of dropdown value. Then on change, i want to dynamically add few elements to the DOM and meantime add required validation for text box based on a condition.

following is the HTML,

<div data-bind="foreach: Properties">
        <div class="control-group">
            <label class="control-label">
                <span class="required" data-bind="visible: IsRequired">*</span>
                <span data-bind="text: Property"></span>
            </label>
            <div class="controls">
                <input type="text" data-bind="value: PropertyValue" />
                <span class="validationMessage" data-bind="validationMessage: PropertyValue"></span>
            </div>
        </div>
</div>

and the subscribe method, (ccVM: my view model)

 ccVM.LevelId.subscribe(function (newValue) {
        if (newValue != null) {
            /*find relevent subitems from an existing observable array*/
            var los = $.grep(ccVM.LevelOfStudies(), function (d) {
                return d.LevelId() == newValue;
            });

            /*clearing existing dynamic array to be populated*/
            ccVM.Properties([]);

            /*add properties to observable array that matched to selected drop down item*/
            if (los.length > 0)
                $.each(los[0].LevelOfStudyProperties(), function (i, prop) {

                    ccVM.Properties.push(new Property({
                        PropertyId: prop.PropertyId(),
                        Property: prop.Property(),
                        IsRequired: prop.IsRequired(),
                        PropertyValue: prop.PropertyValue()
                    }));
                });

        }
    });

below is how i generate Property object,

function Property(data) {
    this.PropertyId = ko.observable(data.PropertyId);
    this.Property = ko.observable(data.Property);
    this.IsRequired = ko.observable(data.IsRequired/*boolean*/);
    /*required validation is not working*/ 
    this.PropertyValue = ko.observable(data.PropertyValue).extend({ required: data.IsRequired/*boolean*/ });
}

though the validation added for dynamic content is not working rest of the validation is working on the page.

Is anybody has any idea how to solve this using knockout validation plugin ?

1

1 Answers

1
votes

You should be using the onlyIf parameter to make the validation conditional. Also, make sure it is pointing to the this.IsRequired observable.

this.PropertyValue = ko.observable(data.PropertyValue).extend({ required: {onlyIf: this.IsRequired }});