验证淘汰赛只有在特定的按钮是pressed [英] Knockout Validation Only If a specific button is pressed

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

问题描述

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

我用我的MCV3页上的淘汰赛验证。我的情况是,我有两个按钮。一个是添加到收藏集,和其他的保存。在添加到收藏集寻找,因为它们都需要以下属性:

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) {

                    }
                });
            }
        }

这是我想要做的事情是,我不希望名字,姓氏,并要求电子邮件,如果保存被调用,仅日期1被验证,但名字,姓氏和电子邮件在需要时AddToCollectoin是调用,但日期1不是。如何设立的唯一如果原来的规则,或者是有这样做的更好的方法。

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.

任何帮助很多AP preciated!

Any help is much appreciated!

推荐答案

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.

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

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