我想用Backbone.validation创建自己的验证器。
我试过这个:
_.extend(Backbone.Validation.validators, {
myValidator: function(value, attr, customValue, model) {
if(value !== customValue){
return 'error';
}
},
});
在我的架构中:
profiles: {
editorClass: "form-inline test",
title: "Skills",
type: 'List',
itemType: 'NestedModel',
model: UserProfile,
render: "buttonsstars",
validators: ['myValidator'],
},
但是,我无法得到任何东西。
答案 0 :(得分:1)
从backbone.validation的文档中,要添加自定义验证程序,首先需要扩展Backbone.Validation.validators
(在模型中使用它之前)。
_.extend(Backbone.Validation.validators, {
myValidator: function(value, attr, customValue, model) {
if(value !== customValue){
return 'error';
}
},
});
然后像这样使用它:
var Model = Backbone.Model.extend({
validation: {
age: {
myValidator: 1 // uses your custom validator
}
}
});
如果自定义验证程序特定于模型,但在验证模式中共享:
var SomeModel = Backbone.Model.extend({
validation: {
name: 'validateName'
},
validateName: function(value, attr, computedState) {/*...snip...*/}
});
如果验证器是针对架构的特定字段的自定义:
var SomeModel = Backbone.Model.extend({
validation: {
name: {
fn: function(value, attr, computedState) {/*...snip...*/}
}
}
});