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

标签 javascript node.js backbone.js

所以我设置了一个新表单,它会临时保存所有内容,但我希望它只能在验证后才能更新,否则会显示一些错误。这是在 saveEdits 事件的 View 部分中,有关于我做错了什么的线索吗?

这是我的 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 并显示错误说明: 未捕获类型错误:无法读取未定义的属性“firstName”

最佳答案

您没有显式调用 validate -- it's meant called by the Backbone framework :

By default validate is called before save, but can also be called before set if {validate:true} is passed.

因此,要修复 OP 中的代码,请在调用 set 时使用 validate: true :

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

<子> 请注意,如果您想调用 validate,则必须向其传递 attrs 参数,如 this.model.validate(this.model.toJSON());

关于javascript - 如何验证在 Backbone 中填写的表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17605570/

相关文章:

javascript - 安装后找不到 gulp run 命令

javascript - 如何在javascript中处理JSON字符串错误(错误字符“)

javascript - 为什么 Node.js 中的哈希对于相同的字符给出不同的结果?

backbone.js - 在backbone.js的另一个 View 中使用时listenTo不起作用

javascript - 在事件回调中获取对模型的引用

javascript - 原型(prototype)对象的构造函数属性

javascript - Angular Controller 调用指令上的函数是 'bad practice' 吗?

node.js - Heroku 上的粘性 session

javascript - 使用 Backbone 和 Node 将模型保存到服务器

javascript - 使用 Backbone 在预输入建议中包含按钮