我一直在关注 Backbone 上的教程,并在此处设置了我的任务项目:
现在在我的单个任务 View 中我有一个验证错误,我 found out here我需要{validation: true}
它的工作原理是它阻止用户输入空值(即:删除当前值)但是我不能阻止用户只输入空格
我的模型和验证方法:
App.Models.Task = Backbone.Model.extend({
validate: function(attrs) {
var errors = this.errors = {};
if (attrs.title != null) {
console.log('title is not null');
if ($.trim(attrs.title) == null) {
alert('error');
console.log('title is required');
}
}
// if ( $.trim(!attrs.title) ) {
// return false;
// }
}
});
这是您设置新值的地方:
editTask: function() {
var newTaskTitle = prompt(this.msgPrompt, this.model.get('title'));
// check for null value
if ( !newTaskTitle ) return;
console.log(newTaskTitle);
this.model.set('title', newTaskTitle, { validate : true });
},
If you notice in my example您可以更改该值并且它起作用,或者尝试删除并提交一个空值并且验证将停止它,但是如果用户只添加空格,您如何有效地不更改该值?
最佳答案
来自fine manual :
validate
model.validate(attributes, options)
[...] If the attributes are valid, don't return anything from validate; if they are invalid, return an error of your choosing. It can be as simple as a string error message to be displayed, or a complete error object that describes the error programmatically.
您问题中的 validate
从不返回任何内容,因此它永远不会捕获无效值。
和$.trim
适用于字符串,而不是 bool 值,所以我不知道这是什么:
if ( $.trim(!attrs.title) ) {
return false;
}
打算做的事。
如果您的验证
看起来更像这样:
validate: function(attrs) {
var errors = { };
if('title' in attrs) {
// Adjust this if you want to allow `null` values.
if($.trim(attrs.title || '') === '') {
errors.title = 'Missing title';
}
}
return _(errors).isEmpty() ? undefined : errors;
}
那么也许你会得到更好的结果。
演示:http://jsfiddle.net/ambiguous/p9ah5/
一些注意事项:
- 我使用
in
operator查看attrs
是否有一个具有任何值的'title'
键。该值可以是null
或false
或0
或'pancakes'
或...我们不关心值是什么,我们只关心它是否存在,所以我们使用in
来准确表达我们的意思。 - 您似乎需要一个对象中的错误消息,所以我们填充一个对象并使用
_.isEmpty
看看我们是否放了什么东西,然后我们就会知道我们应该返回什么。 - Backbone 会将错误放在
validationError
中所以不需要this.error
东西。
关于javascript - Backbone : my validation is not stopping white space being set to value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20449832/