Validating Only Specific Observables

jbeall edited this page Jun 4, 2013 · 1 revision

You can validate only specific observables using the "group" function. For example, if you wanted to validate only the observables viewmodel.firstname and viewmodel.lastname, you could do the following:

var errors = ko.validation.group([viewmodel.firstname, viewmodel.lastname]);

errors will be an array of errors. Note that validation messages will not be displayed unless you also call errors.showAllMessages().

Additionally, the default group validation is "shallow". If you pass an observable that has child items that you wish to be validated, you must also pass an object { deep: true } as the second parameter to group:

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

Notice also that the first parameter does not need to be an array. If you have only a single object, you can pass it in as a bare object, without wrapping it in an array.