【问题标题】:knockout validation on dynamic elements动态元素的淘汰赛验证
【发布时间】:2023-03-09 12:56:01
【问题描述】:

我使用敲除加载了一个下拉列表,并且我使用了订阅事件来处理下拉值的更改。然后在更改时,我想向 DOM 动态添加一些元素,同时根据条件为文本框添加所需的验证。

下面是 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>

和订阅方法,(ccVM:我的视图模型)

 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()
                    }));
                });

        }
    });

下面是我如何生成属性对象,

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*/ });
}

虽然为动态内容添加的验证不起作用,但验证的其余部分正在页面上工作。

有人知道如何使用淘汰赛验证插件解决这个问题吗?

【问题讨论】:

    标签: knockout.js knockout-validation


    【解决方案1】:

    您应该使用onlyIf 参数来使验证有条件。另外,确保它指向 this.IsRequired observable。

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

    【讨论】:

    • 感谢使用 onlyIf 的建议,但最初的问题是动态绑定的元素,提交时动态元素的验证没有被触发 其余的验证都可以。
    猜你喜欢
    • 2016-05-14
    • 2017-09-26
    • 2013-06-23
    • 2012-02-18
    • 2013-01-29
    • 2013-02-18
    • 2011-08-09
    • 1970-01-01
    • 2012-12-25
    相关资源
    最近更新 更多