如何验证Backbone中填写的表单?

时间:2013-07-12 00:06:17

标签: javascript node.js backbone.js

所以我有一个新的表单设置它临时保存,但我希望它只能在验证时更新,否则显示一些错误。这是在saveEdits事件的视图部分期间任何关于我做错了什么的线索?

这是我的main.js文件

(function () {
    window.App = {
        Models: {},
        Collections: {},
        Views: {},
        Templates: {},
        Router: {}

    };

    // MODEL
    App.Models.User = Backbone.Model.extend({
        defaults: {
            firstName: 'first',
            lastName: 'last',
            email: 'Email',
            phone: '222',
            birthday: '07/22/1980'
       },

        validate: function (attrs) {

            if (!attrs.firstName) {
                return 'You must enter a real first name.';
            }
            if (!attrs.lastName) {
                return 'You must enter a real last name.';
            }
            if (attrs.email.length < 5) {
                return 'You must enter a real email.';
            }
            if (attrs.phone.length < 10 && attrs.phone === int) {
                return 'You must enter a real phone number, if you did please remove the dash and spaces.';
            }
            if (attrs.city.length < 2) {
                return 'You must enter a real city.';
            }
        },

        initialize: function() {
             this.on('invalid', function (model, invalid) {
                console.log(invalid);
            });
        }

    });

    //var userModel = new App.Models.User();

    //VIEW
    App.Views.User = Backbone.View.extend({
        el: '#user',
        //model: userModel,
        //tagName: 'div',
        //id: 'user',
        //className: 'userProfile',
        //template: _.template($("#userTemplate").html()),
        //editTemplate: _.template($("#userEditTemplate").html()),


        initialize: function (){

        },

        render: function() {
            this.template = Handlebars.compile($("#userTemplate").html());
            this.editTemplate = Handlebars.compile($("#userEditTemplate").html());

            this.$el.html(this.template(this.model.toJSON()));
            return this;
        },

        events: {
            'click button.edit': 'editProfile',
            'click button.save': 'saveEdits',
            'click button.cancel': 'cancelEdits'
        },

        editProfile: function () {
            this.$el.html(this.editTemplate(this.model.toJSON()));

        }, 

        saveEdits: function () {
            var form = $(this.el).find('form#updateUser');
            this.model.set({

                firstName : form.find('.firstName').val(),
                lastName : form.find('.lastName').val(),
                email: form.find('.email').val(),
                phone: form.find('.phone').val(),
                birthday: form.find('.birthday').val()

            });

            this.model.validate();

            this.render();

        },

        cancelEdits: function() {
            this.render();
        }

    });
    //start history service
    Backbone.history.start();

    var user = new App.Views.User({model: new App.Models.User()});
    user.render();
})();

它工作正常,直到我插入this.model.validate并出现错误,说明这一点: Uncaught TypeError: Cannot read property 'firstName' of undefined

1 个答案:

答案 0 :(得分:2)

您未明确致电validate - it's meant called by the Backbone framework

  

默认情况下,在保存之前调用validate,但如果传递了{validate:true},也可以在set之前调用。

为了修复OP中的代码,请在set的调用中使用validate: true

this.model.set({ 
    firstName : form.find('.firstName').val(),
    // ...
}, { validate: true });

<子> 请注意,如果您要调用validate,则必须将attrs参数传递给它,如this.model.validate(this.model.toJSON());中所示