Knockout Validation Only If a specific button is pressed

送分小仙女□ 提交于 2019-12-31 03:47:10

问题


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

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:

first:

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

and second:

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

                    }
                });
            }
        }

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.

Any help is much appreciated!


回答1:


The onlyIf option could work here:

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

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



来源:https://stackoverflow.com/questions/14217921/knockout-validation-only-if-a-specific-button-is-pressed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!