我正在学习backbone.js并试图弄清楚如何使用验证方法。但我的问题是,当我调用验证时,触发了验证,但它仍然保存了无效数据。如此处player.set('firstName', '', { validate: true });
所示,我将lastName变量设置为''并且它保存了这些值,它不应该。
修改 - 更新了代码,现在它可以正常运行 骨干模型。
var Player = Backbone.Model.extend({
defaults: {
firstName: "Not specified",
lastName: "Not specified",
position: "Not specified"
},
validate: function (attributes) {
// validate first name
if (!attributes.firstName || attributes.firstName === '') {
return 'you must have a first name';
}
// validate last name
if (!attributes.lastName || attributes.lastName === '') {
return 'you must provide a last name.';
}
// validate position
if (!attributes.position || attributes.position === '') {
return 'you must provide a position.';
}
},
initialize: function () {
// checks when firstName has changed
this.on('change:firstName', function () {
console.log("firstName attribute has changed.");
});
// checks when lastName has changed
this.on('change:lastName', function () {
console.log("lastName attribute has changed.");
});
// checks when position has changed
this.on('change:position', function () {
console.log("position attribute has changed.");
});
// check for valid inputs
this.on('error', function (model, error) {
console.log(error);
});
}
});
在chrome dev工具中,我执行以下代码。
var player = new Player;
player.set({ firstName: "peter", lastName: "andrews", position: "outfield" }, { validate: true });
player.toJSON();
firstName attribute has changed. app.js:32
lastName attribute has changed. app.js:36
position attribute has changed. app.js:40
Object {firstName: "peter", lastName: "andrews", position: "outfield"}
player.set('firstName', '', { validate: true });
player.toJSON();
you must have a first name app.js:14
Object {firstName: "peter", lastName: "andrews", position: "outfield"}
答案 0 :(得分:2)
如果属性有效,请不要从验证中返回任何内容;如果 它们无效,返回您选择的错误。
您的验证功能是使用console.log
打印错误字符串,但不返回任何内容。
尝试将validate
功能更改为:
validate: function (attributes) {
// validate first name
if (!attributes.firstName || attributes.firstName === '') {
return 'you must have a first name';
}
// validate last name
if (!attributes.lastName || attributes.lastName === '') {
return 'you must provide a last name.';
}
// validate position
if (!attributes.position || attributes.position === '') {
return 'you must provide a position.';
}
},