问题
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