Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extender 'ignoreInValidationGroup' to guard observables from being added to validation groups #224

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 13 additions & 0 deletions Src/knockout.validation.js
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,11 @@
// if object is observable then add it to the list
if (ko.isObservable(obj)) {

//but not if it is flagged as ignore in group
if(obj.ignoreInValidationGroup) {
return; // we also do not add descendants
}

//make sure it is validatable object
if (!obj.isValid) obj.extend({ validatable: true });
validatables.push(obj);
Expand Down Expand Up @@ -939,6 +944,14 @@
return observable;
};

//This extender can be used to flag a Knockout Observable to be ignored in validation groups.
//When the extender is set the observable will not be added to validation groups.
//Rules added to a flagged obserable still apply but the errors are not shown in any group.
ko.extenders['ignoreInValidationGroup'] = function (observable, enable) {
observable.ignoreInValidationGroup = enable;
return observable;
};

function validateSync(observable, rule, ctx) {
//Execute the validator and see if its valid
if (!rule.validator(observable(), ctx.params === undefined ? true : ctx.params)) { // default param is true, eg. required = true
Expand Down
12 changes: 12 additions & 0 deletions Tests/validation-tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -1038,6 +1038,18 @@ test('Issue #37 - Toggle ShowAllMessages', function () {
ok(!vm.two.one.isModified(), "Level 2 is not modified");
ok(!vm.three.two.one.isModified(), "Level 3 is not modified");
});

test('grouping ignores observables extended with ignoreInValidationGroup', function () {
var vm = {};
vm.firstName = ko.observable().extend({ required: true });
vm.lastName = ko.observable().extend({ required: 2 });
vm.allProperties = ko.observableArray([vm.firstName, vm.lastName]).extend({ ignoreInValidationGroup: true });

var errors = ko.validation.group(vm, { deep: true, observable: true });

equals(errors().length, 2, 'Grouping correctly finds only 2 invalid properties');
});

//#endregion

//#region Conditional Validation
Expand Down