Backbone.js模型验证,不知道这里有什么问题?

时间:2013-07-06 00:06:28

标签: javascript validation backbone.js

我不知道为什么错误不会弹出或禁止发生这样的事情。我试图弄清楚如何验证这个骨干模型。将它用于客户端并使用它进行学习。

目前正在设置一个没有任何内容的字符串。

var user = new User();
user.set({'firstName': ''}, {validate:true});

我的骨干代码

var User = Backbone.Model.extend({
    defaults: {
        firstName: 'J.R.',
        lastName: 'Smith',
        email: 'jsmith@knicks.com',
        phone: '212-424-6234',
        birthday: '03/05/1982',
        city: 'New York'

    },

    validate: function(attrs) {
        if(!attrs.firstName) {
            return 'You must enter a real name.'
        },
        if(!attrs.lastName) {
            return 'You must enter a real 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.'
        },
    },

    location: function(){
        return this.get('firstName') + ' ' + this.get('lastName') + 'is currently in ' + this.get('city') + '.';
    },

    initialize: function() {



        this.on('invalid', function(model, invalid){
            console.log(invalid);
            //when setting a user user.set('age', -55, {validate : true}); the validate true makes sure it validates
        });
    },

});

1 个答案:

答案 0 :(得分:0)

您的验证功能是语法错误。在每个if语句之后,您不需要使用“,”,因为这是一个函数而不是对象文字。

    validate: function(attrs) {
        if(!attrs.firstName) {
            return 'You must enter a real name.'
        }
        if(!attrs.lastName) {
            return 'You must enter a real 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.'
        }
    },