Knockout Mapping Validation

淺唱寂寞╮ 提交于 2019-11-30 03:12:38

I have found at least two ways to supply validations to model or view model objects that are created via the ko.mapping plugin:

  1. Use the mapping options to attach the validation rules when certain properties are created
  2. HTML5 attributes. This is only supported for some validations (i.e. required, pattern). See the documentation for the Knockout-Validation plugin for details

The above two techniques can also be combined. See the following fiddle for an example.


1. Using Mapping Options

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

<input data-bind="value: name" />


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);


2. HTML5 Attributes

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

<input data-bind="value: name" required />


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);

Another way is to extend the observable after it has mapped.

function viewModel() {
    var self = this;
    self.persons = ko.observableArray();

    // persons are retrieved via AJAX...
    ko.mapping.fromJS(persons, {}, self.persons);


    self.Name.extend({ required: true });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!