use*_*269 20 knockout-mapping-plugin knockout.js knockout-validation
我正在尝试将验证附加到映射视图.我正在使用Knockout Mapping and Validation插件.少女模特儿:
Person {
int Id;
string Name;
Book[] Books;
}
Book {
int Id;
string Name;
}
Run Code Online (Sandbox Code Playgroud)
使用Javascript:
function viewModel() {
var self = this;
self.persons = ko.observableArray();
// persons are retrieved via AJAX...
ko.mapping.fromJS(persons, {}, self.persons);
}
jQuery(function( $ ) {
ko.applyBindings(new viewModel());
});
Run Code Online (Sandbox Code Playgroud)
如何扩展observableArray人员以设置验证规则和消息?我需要验证人员和书籍子数组属性.我发现只有使用显式模型设置的示例,没有自动映射,例如:
Name: ko.observable().extend({ required: true })
Run Code Online (Sandbox Code Playgroud)
然后我需要设置ko.validatedObservable,isValid和validation.init,但我真的不知道如何处理/组织这个.你能帮忙吗?
Jus*_*zer 30
我找到了至少两种方法来提供验证来建模或查看通过ko.mapping插件创建的模型对象:
上述两种技术也可以组合使用.有关示例,请参阅以下小提琴.
Knockout Mapping插件允许在要定制的映射对象上创建某些属性.利用此功能,您可以覆盖插件的默认行为并为映射的属性添加验证.以下是一个例子
HTML
<input data-bind="value: name" />
Run Code Online (Sandbox Code Playgroud)
使用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);
Run Code Online (Sandbox Code Playgroud)
Knockout Validation插件支持一组有限的HTML5验证属性,可以在HTML控件中使用.但是,使用它们需要启用该parseInputAttributes选项.这是一个简单的例子:
HTML
<input data-bind="value: name" required />
Run Code Online (Sandbox Code Playgroud)
使用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);
Run Code Online (Sandbox Code Playgroud)