1

我想用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'],
},

但是,我什么也得不到。

4

1 回答 1

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...*/}
    }
  }
});
于 2016-11-09T15:55:21.273 回答