仅当按下特定按钮时才进行淘汰赛验证 [英] Knockout Validation Only If a specific button is pressed

查看:18
本文介绍了仅当按下特定按钮时才进行淘汰赛验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

https://github.com/ericmbarnard/Knockout-Validation/wiki/本地规则

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

I am using the knockout validation on my MCV3 page. The situation I have is that I have two buttons. one is Add To Collection, and other is Save. The Add to collection looks for following properties as they are required:

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 }),

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

I have two functions defined that check if the page is valid:

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,但是当 AddToCollectoin 为 FirstName、LastName 和 Email 时需要 FirstName、LastName 和 Email调用,但 Date1 不是.如何设置 Only If Native 规则,或者有更好的方法来做到这一点.

The thing that I am trying to do is that I don't want the FirstName, LastName, and Email to be required if Save is called, only Date1 is validated, but FirstName, LastName, and Email is required when AddToCollectoin is called, but Date1 is not. How do set up the Only If Native Rule, or is there a better way of doing this.

非常感谢任何帮助!

推荐答案

onlyIf 选项可以在这里工作:

The onlyIf option could work here:

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

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

You would need to set the someFlagIsTrue from your click event or other means.

这篇关于仅当按下特定按钮时才进行淘汰赛验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆