gpt4 book ai didi

javascript - Backbone.js 模型验证,不知道这里出了什么问题?

转载 作者:行者123 更新时间:2023-11-28 09:02:50 25 4
gpt4 key购买 nike

我不知道为什么错误没有弹出或禁止类似的事情发生。我正在尝试弄清楚如何验证这个 Backbone 模型。将其用于客户端并从中学习。

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

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

});

最佳答案

您的验证函数存在语法错误。您不需要在每个 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.'
}
},

关于javascript - Backbone.js 模型验证,不知道这里出了什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17498317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com