1

我不知道为什么错误没有弹出或禁止这样的事情发生。我试图弄清楚如何在这个骨干模型上进行验证。将其用于客户端并与之一起学习。

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

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
        });
    },

});
4

1 回答 1

0

您的 validate 函数作为语法错误。您不需要在每个 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.'
        }
    },
于 2013-07-06T01:51:35.147 回答