【问题标题】:Knockout-Validation - Date greater than another date淘汰赛验证 - 日期大于另一个日期
【发布时间】:2015-11-17 01:27:46
【问题描述】:

我一直在研究使用剔除验证来比较日期的不同方法。我无法让它与我在验证的Observable 对象中的 obervable 一起工作。

我需要 validateObservable 来检查按钮单击时验证是否通过/失败 - 这是我的控件分组。

这是我的演示:

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/knockout-2.3.0.js"></script>
<script src="~/Scripts/knockout.validation.min.js"></script>
<script src="~/Scripts/moment.min.js"></script>
<form>
    <table>
        <tr>
            <td>Name:</td>
            <td><input type="text" data-bind="value:contactForm().name" value="" /></td>
        </tr>
        <tr>
            <td>From:</td>
            <td><input type="text" data-bind="value:contactForm().fromDate" value="" /></td>
        </tr>
        <tr>
            <td>To:</td>
            <td><input type="text" data-bind="value:contactForm().toDate" /></td>
        </tr>
    </table>
    <button type="button" data-bind='click: submit'>Submit</button>
</form>
<script>

    ko.validation.init({
        messagesOnModified: false,
        parseInputAttributes: true,
        grouping: {
            deep: true
        }
    });

    var myViewModel = function () {
        var self = this;
        self.contactForm = ko.validatedObservable({
                name :ko.observable().extend({ required: true }),
                fromDate :ko.observable('2014-11-10').extend({ date: true }),
                toDate: ko.observable('2014-11-10').extend({date: true, min: this.fromDate })
            });
            submit = function () {
                console.log(this.contactForm.isValid())
            };
        };

        ko.applyBindings(new myViewModel());

</script>

我基本上无法让这条线工作:

toDate: ko.observable('2014-11-10').extend({date: true, min: this.fromDate })

有人有什么想法吗?

【问题讨论】:

    标签: knockout.js knockout-validation


    【解决方案1】:

    这是因为您在创建对象字面量时使用了 this(当您在 toDate 声明中引用 fromDate 时),并且在构造该对象时,this 仍然指的是封装函数上下文( myViewModel 在这种情况下)。

    试试这个(基于this answer):

    self.contactForm = ko.validatedObservable({
                name: ko.observable().extend({ required: true }),
                fromDate: ko.observable('2014-11-10').extend({ date: true }),
                toDate: ko.observable('2014-11-10'),
                init: function() {
                    this.toDate = this.toDate.extend({date: true, min: this.fromDate});
                    return this;
                }
            }.init());
    

    【讨论】:

    • 谢谢你,花了好几个小时
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 2012-11-09
    • 2014-10-12
    • 2012-05-26
    相关资源
    最近更新 更多