I\'m trying to attach validation to a mapped view. I\'m using Knockout Mapping and Validation plugins. Pseudo-models:
Person {
int Id;
string Name;
I have found at least two ways to supply validations to model or view model objects that are created via the ko.mapping plugin:
The above two techniques can also be combined. See the following fiddle for an example.
The Knockout Mapping plugin allows the creation of certain properties on mapped objects to be customized. Taking advantage of this functionality, you can override the default behavior of the plugin and add validation for your mapped properties. Below is an example
HTML
Javascript
var data = { name: "Joe Shmo" };
var validationMapping = {
// customize the creation of the name property so that it provides validation
name: {
create: function(options) {
return ko.observable(options.data).extend( {required: true} );
}
}
};
var viewModel = ko.validatedObservable(ko.mapping.fromJS(data, validationMapping));
ko.applyBindings(viewModel);
The Knockout Validation plugin supports a limited set of HTML5 validation attributes that can be used in your HTML controls. However, using them requires enabling the parseInputAttributes option. Here is a simple example:
HTML
Javascript
// this can also be configured through the "validationOptions" binding (https://github.com/ericmbarnard/Knockout-Validation/wiki/Validation-Bindings)
ko.validation.configure({
parseInputAttributes: true
});
var data = { name: "Joe Shmo" };
var viewModel = ko.validatedObservable(ko.mapping.fromJS(data));
ko.applyBindings(viewModel);