在向骨干集合添加数据之前验证表单中的数据

时间:2013-09-14 15:19:23

标签: validation backbone.js backbone-views backbone-events

嗨,我是骨干的新手。 我正在尝试关注http://listen-dom-events-backbone.herokuapp.com/。 我编辑了html,以便输入三个属性:姓名年龄和职业

<form id="addPerson" action="">
        <input type="text" placeholder="Name of the person" id="name">
        <input type="text" placeholder="Age" id="age">          
        <input type="text" placeholder="Occupation" id="occ">
        <input type="submit" value="Add Person">
</form>
    <script id="personTemplate" type="text/template">
<span><strong><%= name %></strong> (<%= age %>) - <%= occupation %></span> 
<button class="edit">Edit</button>
<button class="delete">Delete</button>
    </script>

我骨干的验证是这样的。

App.Views.AddPerson = Backbone.View.extend({
el: '#addPerson',

events: {
    'submit': 'submit'
},

submit: function(e) {
    e.preventDefault();
    var newPersonName = $(e.currentTarget).find('input[type=text]').val();
    var newage = $(e.currentTarget).find(age).val();
    var newocc = $(e.currentTarget).find(occ).val();
    var person = new App.Models.Person({name: newPersonName, age: newage, occupation: newocc});

            // Only when the data exists it has to be added to the collection
            // This is what i tried

           // Method 1: 
    var attributes = person.attributes();
    validate: function(){
        if(attributes.newage ==null){alert("Please Enter Age")}
    if(attributes.newocc ==null){alert("Please enter occupation")}      
    }

            //Method 2
            var attributes = person.attributes();
    validate: function(attributes){
        if(attributes.newage !=null){person.set({age: newage});}
        if(attributes.newocc !=null){person.set({occupation: newocc});
            }

            // Only if everything above is correct this value should be returned
    this.collection.add(person);

}

});

我这样做是对还是有问题?

1 个答案:

答案 0 :(得分:2)

验证应该在模型中完成,这就是骨干的设计方式。如果您查看文档,您会发现模型中有validate方法,isValid方法以及validationError属性,当您覆盖validate方法。 因此,validate模型中的Person方法可以像这样定义。

App.Models.Person = Backbone.Model.extend({
  // some other methods
  validate: function(attributes, options) {
    var errors = [];
    if(_.isEmpty(attributes.age)) {
      errors.push("age missing");
    }
    if(_.isEmpty(attributes.occupation)) {
      errors.push("occupation missing");
    }
    if(!_.isEmpty(errors)) {
      return errors;
    }
  }
});

然后,您就可以在模型上调用isValid,如果不是,则validate方法返回的验证错误将通过validationError属性提供。然后,您可以将提交方法更改为以下内容:

 submit: function(e) {
    e.preventDefault();
    if(this.model.isValid()) {
      // do what you want with your model
    } else {
      alert(this.model.validationError.join('\n'));
    }
  }