Backbone验证插件无法验证

时间:2014-10-26 12:17:00

标签: javascript jquery validation backbone.js

我使用Backbone.Validation插件验证简单表单。以下是我的模特

var BuyerModel = Backbone.Model.extend({
    defaults: {
        name: '',
        age: ''
    },

    validation: {
        name: {
            required: true
        },
        age: { 
            min: 18
        }
    },

    initialize: function () {
        _.extend(Backbone.Model.prototype, Backbone.Validation.mixin);
    }

});

以下是我的观点

var BuyerModelFormView = Backbone.View.extend({

    events: {
        'click [name~="save"]': 'save'
    },

    initialize: function () {
        Backbone.Validation.bind(this);
    },

    template: _.template('\
         <form>\
               Enter name:\
               <input name="name" type="text" value="<%= name %>"><br>\
               Enter age:\
               <input name="age" type="text" value="<%= age %>"><br>\
               <input type="button" name="save" value="Save">\
        </form>\ '),

    render: function () {
        var html = this.template(this.model.toJSON());
        $(this.el).html(html);
    },

    save: function () {
        console.log(this.model.toJSON());
        this.model.set({
            name: $('[name~="name"]').val(),
            age: $('[name~="age"]').val()
        });

        console.log(this.model.toJSON());
    }

});

以下是我使用它的方式

    var buyerModel = new BuyerModel();

    var buyerModelFormView = new BuyerModelFormView({
        model: buyerModel,
        el: 'body'
    });

    buyerModelFormView.render();

当我在表单中输入任何内容并点击输入时更新模型但不验证。即使我输入不正确的值模型仍然会更新。

我做错了什么,我该如何解决?

1 个答案:

答案 0 :(得分:4)

像这样设置强制验证

this.model.set({
    name: $('[name~="name"]').val(),
    age: $('[name~="age"]').val()
}, {validate: true});

这是你想要的吗?

因为Model.set有这样的字符串

// Run validation.
      if (!this._validate(attrs, options)) return false;

并且

// Run validation against the next complete set of model attributes,
// returning `true` if all is well. Otherwise, fire an `"invalid"` event.
_validate: function(attrs, options) {
  if (!options.validate || !this.validate) return true;

因此,如果您没有通过验证 - 它将被忽略

以这种方式检查

$(function(){
    var buyerModel = new BuyerModel();

    buyerModel.on('change', function(){
        console.log('on change', arguments);
    });

    var buyerModelFormView = new BuyerModelFormView({
        model: buyerModel,
        el: 'body'
    });

    buyerModelFormView.render();
});