gpt4 book ai didi

javascript - 主干模型在错误验证时设置值

转载 作者:行者123 更新时间:2023-11-30 17:37:57 25 4
gpt4 key购买 nike

我正在学习 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 开发工具中执行以下代码。

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"}

最佳答案

来自Backbone docs :

If the attributes are valid, don't return anything from validate; if they are invalid, return an error of your choosing.

您的验证函数正在使用 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.';
}
},

关于javascript - 主干模型在错误验证时设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21656246/

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