【问题标题】:Knockout Validation Only If a specific button is pressed仅当按下特定按钮时才进行淘汰验证
【发布时间】:2012-12-22 11:30:05
【问题描述】:

https://github.com/ericmbarnard/Knockout-Validation/wiki/Native-Rules

我在我的 MCV3 页面上使用淘汰赛验证。我的情况是我有两个按钮。一个是添加到收藏夹,另一个是保存。添加到集合会根据需要查找以下属性:

FirstName: ko.observable().extend({ required: true }),
LastName: ko.observable().extend({ required: true }),
Title: ko.observable(),
Email: ko.observable().extend({ required: true, email: true }),
Date1: ko.observable(new Date()).extend({ required: true }),

我定义了两个函数来检查页面是否有效:

第一:

AddToCollection: function () {
            if (!viewModel.isValid()) {
                viewModel.errors.showAllMessages();
                return false;
            } else {
                this.Collection.push(new Item(this.FirstName(), this.LastName(), this.Title(), this.Email()));
                viewModel.clear();
            }
        },

第二个:

save: function () {
            if (!viewModel.isValid()) {
                viewModel.errors.showAllMessages();
                return false;
            } else {
                $.ajax({
                    url: '@Url.Action("DoSomethinn")',
                    type: "POST",
                    data: ko.toJSON(this),
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function (result) {

                    }
                });
            }
        }

我想要做的事情是,如果调用 Save,我不希望需要 FirstName、LastName 和 Email,仅验证 Date1,但在 AddToColletoin 时需要 FirstName、LastName 和 Email调用,但 Date1 不是。如何设置 Only If Native Rule,或者有更好的方法。

非常感谢任何帮助!

【问题讨论】:

  • 试图提供帮助 - 您可以发布一个指向 jsFiddle/jsBin 的链接,然后我们可以为您修复它

标签: asp.net-mvc-3 knockout.js knockout-validation


【解决方案1】:

onlyIf 选项可以在这里工作:

FirstName: ko.observable().extend({ 
    required: {
        params: true,
        onlyIf: function(){ return someFlagIsTrue; }
    }

您需要通过点击事件或其他方式设置someFlagIsTrue

【讨论】:

    猜你喜欢
    • 2013-01-21
    • 2023-03-25
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    相关资源
    最近更新 更多