Reputation: 8132
I have one VM which has multiple forms with all validation. To support multiple forms i think i have to implement knockout optional validation.
There are many validations in my forms. Like maxLength
, minlength
,required
and one custom validation.
The validations looks like this
@password = ko.observable("").extend({ required: true, minLength: 5})
@current_password = ko.observable().extend({
validation: { validator: @mustEqual, message: 'Passwords do not match.', params: @password }
})
Now, to make the above validation optional with isLoggedIn
i use this
@password = ko.observable().extend
required:
onlyIf: () =>
!@isLoggedIn()
but it only works for required
. i also want it for minLength
and for custom validator
. How to do that ?
Upvotes: 1
Views: 2679
Reputation: 4735
onlyIf can be used with all validators, like this (fiddle, forked from github examples: http://jsfiddle.net/LYP5u/25/):
self.testField = ko.observable(5).extend({
max:{
onlyIf:function() { return self.country() === 'US'},
params:5
}
});
Example from validation source: https://github.com/Knockout-Contrib/Knockout-Validation/blob/master/Src/api.js#L225
Conditional validation docs: https://github.com/Knockout-Contrib/Knockout-Validation/wiki/Conditional-Validation-with-onlyIf-parameter
Maybe we should talk to one of the maintainers to make this more clear in the manual, perhaps add some examples with onlyIf to this page https://github.com/Knockout-Contrib/Knockout-Validation/wiki/Native-Rules
Upvotes: 3