Javascript 如何验证在主干中填写的表单?

Javascript 如何验证在主干中填写的表单?,javascript,node.js,backbone.js,Javascript,Node.js,Backbone.js,所以我设置了一个新表单,它会临时保存,但我希望它只能在验证后更新,否则会显示一些错误。这是在saveEdits事件的查看部分,有没有关于我做错了什么的线索 这是我的main.js文件 (function () { window.App = { Models: {}, Collections: {}, Views: {}, Templates: {}, Router: {} }; // MO

所以我设置了一个新表单,它会临时保存,但我希望它只能在验证后更新,否则会显示一些错误。这是在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();
})();
(函数(){
window.App={
型号:{},
集合:{},
视图:{},
模板:{},
路由器:{}
};
//模型
App.Models.User=Backbone.Model.extend({
默认值:{
名字:'第一',
lastName:“last”,
电子邮件:“电子邮件”,
电话:"222",,
生日:1980年7月22日
},
验证:函数(attrs){
如果(!attrs.firstName){
return“您必须输入真实的名字”;
}
如果(!attrs.lastName){
return“您必须输入真实的姓氏”;
}
如果(attrs.email.length<5){
return“您必须输入真实的电子邮件”;
}
if(attrs.phone.length<10&&attrs.phone==int){
return“您必须输入真实的电话号码,如果输入了,请删除破折号和空格。”;
}
如果(属性城市长度<2){
返回“您必须进入一个真实的城市”;
}
},
初始化:函数(){
this.on('invalid',函数(model,invalid){
console.log(无效);
});
}
});
//var userModel=new App.Models.User();
//看法
App.Views.User=Backbone.View.extend({
el:“#用户”,
//model:userModel,
//标记名:“div”,
//id:'用户',
//类名:“userProfile”,
//模板:35;.template($(“#userTemplate”).html()),
//editTemplate:35;.template($(“#userEditTemplate”).html(),
初始化:函数(){
},
render:function(){
this.template=handlebar.compile($(“#userTemplate”).html();
this.editTemplate=handlebar.compile($(“#userEditTemplate”).html();
this.el.html(this.template(this.model.toJSON());
归还这个;
},
活动:{
'单击按钮。编辑':'编辑配置文件',
'单击按钮。保存':'保存编辑',
'单击按钮。取消':'取消编辑'
},
editProfile:函数(){
this.el.html(this.editTemplate(this.model.toJSON());
}, 
保存编辑:函数(){
var form=$(this.el).find('form#updateUser');
这个。模型。集合({
firstName:form.find('.firstName').val(),
lastName:form.find('.lastName').val(),
电子邮件:form.find('.email').val(),
phone:form.find('.phone').val(),
生日:form.find('.birth').val()
});
this.model.validate();
这个。render();
},
取消编辑:函数(){
这个。render();
}
});
//启动历史记录服务
Backbone.history.start();
var user=new App.Views.user({model:new App.Models.user()});
user.render();
})();
在我插入this.model.validate并显示一个错误之前,它工作正常:
未捕获类型错误:无法读取未定义的属性“firstName”

您没有显式调用
validate

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

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


注意,如果要调用validate,则必须向其传递
attrs
参数,如
this.model.validate(this.model.toJSON())

谢谢,您知道我为什么会出现此错误吗?未捕获的TypeError:无法读取未定义的属性'length',我在我的模型的验证函数中调用它是否错误?@Lion789好吧,例如没有“city”,因此您不能调用
city.length
,而不会得到错误。你需要检查一下。如,
if(typeof attr.city==“undefined”| | attr.city.length<2)
。我确实这样做了,而且似乎有效,电话:{length:10 if(length:10 if)(一个小建议-我建议绑定到表单上的'submit'事件,而不是保存按钮上的'click',以防用户的浏览器可以在不显式引发该按钮上的“单击”事件的情况下提交表单。
this.model.set({ 
    firstName : form.find('.firstName').val(),
    // ...
}, { validate: true });