如何使用Backbone.validation添加我自己的验证器?

时间:2016-11-09 11:29:13

标签: javascript backbone.js backbone.validation.js

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

但是,我无法得到任何东西。

1 个答案:

答案 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...*/}
    }
  }
});