【问题标题】:How to validate model using collection.create()如何使用 collection.create() 验证模型
【发布时间】:2014-09-16 14:34:19
【问题描述】:

我正在尝试在提交之前验证表单。为此,我在 View 中定义了一个 create 方法,该方法负责调用 collection.create() 方法来创建模型。

这是一个示例代码:

app.ContactCreateView = Backbone.View.extend({
    template: _.template($('#tpl-create-contact').html()),
    initialize: function () {
      this.router = new app.ContactsRouter();
      this.contacts = new app.ContactsCollection();
    },
    events: {
      'click #btn-create' : 'create',
      'click #btn-cancel' : 'cancel',
    },
    render: function() {
      this.$el.html(this.template());
      return this;
    },
    getAttributes: function () {
      console.log('getAttributes()');
      var attr = { 
        name: $('#input-name').val().trim(),
        category: $('#input-category').val().trim(),
        phone: $('#input-phone').val().trim(),
        email: $('#input-email').val().trim(),
      };
      console.log('attr : ' + JSON.stringify(attr))
      return attr;
    },
    create: function () {
      console.log('create()');
      // Create the Model
      this.contacts.create(this.getAttributes(), {
        wait : true,      
        success: function () {
          console.log('success');
          //this.hideErrors();
          var router = new app.ContactsRouter();
          router.navigate('contacts', true);
        },
        error: function () {
          console.log('error(s)')
          //this.showErrors(errors);
        }
      });

    },

“成功”回调被很好地调用了,但是一旦 model.validate() 方法失败,我就无法调用“错误”回调。

这是带有验证方法的模型:

app.ContactModel = Backbone.Model.extend({
    urlRoot: '/user',
    // Default attributes for the Contact
    defaults: {
      name: null,
      phone: null,
      email: null,
      category: null,
      photo: "/images/placeholder.png"
    },
    validate: function(attrs) {
      console.log('validate() : ' + JSON.stringify(attrs));
      var errors = [];
      if (!attrs.name) {
        errors.push({name: 'name', message: 'Please fill name field.'});
      }
      if (!attrs.category) {
        errors.push({name: 'category', message: 'Please fill category field.'});
      }
      console.log('errors : ' + JSON.stringify(errors));
      return errors.length > 0 ? errors : false;
    }
  });

还有收藏:

  app.ContactsCollection = Backbone.Collection.extend({
    model: app.ContactModel,
    url: '/user',
    //localStorage: new Backbone.LocalStorage('contacts-backbone'),

    getById: function (iId) {
        return this.where({id: iId});
    },
    getByName: function (iName) {
        return this.where({name: iName});
    }
  });

我真的不明白我做错了什么......如果有人可以帮助我:-( 问候,

【问题讨论】:

    标签: validation backbone.js


    【解决方案1】:

    当验证失败错误回调未被调用时,它会在模型​​上触发“无效”事件,并在模型上设置validationError属性。

    方法一(监听模型):

    app.ContactModel = Backbone.Model.extend({
        urlRoot: '/user',
       //your error catched here
       initialize : function(){
            this.on("invalid",function(model,error){
                alert(error);
            });
        defaults: {
          name: null,
          phone: null,
          email: null,
          category: null,
          photo: "/images/placeholder.png"
        },
        validate: function(attrs) {
          console.log('validate() : ' + JSON.stringify(attrs));
          var errors = [];
          if (!attrs.name) {
            errors.push({name: 'name', message: 'Please fill name field.'});
          }
          if (!attrs.category) {
            errors.push({name: 'category', message: 'Please fill category field.'});
          }
          console.log('errors : ' + JSON.stringify(errors));
          return errors.length > 0 ? errors : false;
        }
      });
    

    方法2(检查你的视图是否设置了validationError属性):

         create: function () {
          console.log('create()');
          // Create the Model
          this.contactModel.save(this.getAttributes(), {
            wait : true,      
            success: function () {
              console.log('success');
              this.contacts.add(this.contactModel);
              var router = new app.ContactsRouter();
              router.navigate('contacts', true);
            },
            error: function () {
              console.log('error(s)')
            }
          });
          //your error catched here
          if (this.contactModel.validationError) {
          alert(this.contactModel.validationError)
        }
        },
    

    【讨论】:

      【解决方案2】:

      所以我在一个我目前正在开发的应用程序中玩了一段时间,发现它有点烦人,从来没有真正让它发挥作用。

      相反,我选择了jQuery validation 路线,发现它对进行验证非常有帮助。我强烈建议检查一下!它有很多内置验证,您可以直接使用,您还可以覆盖显示的错误消息(也是内置的)。

      示例 - 我想要一个仅限数字的文本字段(请原谅咖啡脚本):)。

      jQuery.validator.setDefaults(
                  debug: true,
                  success: "valid")
              if @model.get('number_only')
                  $('#number_only').validate({
                      debug: true,
                      rules: {
                          "number[entry]": {
                              required: true,
                              range: [@model.get('min_number'), @model.get('max_number')],
                              number: true
                          }
                      },
                      messages: {
                          "number[entry]": {
                              required: "This field is required. Please enter a numeric value.",
                              min: jQuery.validator.format("Please enter a value greater than or equal to {0}."),
                              max: jQuery.validator.format("Please enter a value less than or equal to {0}."),
                              number: "Please enter a numeric value"
                              range: jQuery.validator.format("Please enter a value between {0} and {1}.")
                          }
                      }
                  })
      

      如果这并没有真正得到您想要的(似乎您可能对显示您的服务器发回的错误更感兴趣,而这条路线更多地是在保存您的模型之前验证内容)让我知道,我可以看到如果我能找出你的问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-07-13
        • 2014-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-22
        相关资源
        最近更新 更多