主干验证功能没有被调用 [英] Backbone validate function not getting called
问题描述
我的验证函数没有在下面的代码中被调用:-
My validate function is not getting called in the code below:-
var Vehicle = Backbone.Model.extend({
color: 'green',
validate: function (attrs) {
var validColors = ['white', 'red', 'blue', 'yellow'];
var colorIsValid = function (attrs) {
if (!attrs.color) return true;
return _.contains(validColors, attrs.color);
}
if(!colorIsValid(attrs)) {
return "color must be one of: " +validColors.join(",");
}
}
});
var car = new Vehicle();
car.on('error', function (model, error) {
console.log(error);
});
console.log(car.get('color'));
car.set('color', 'muave');
请看小提琴http://jsfiddle.net/vineet85/Fa8jr/5/
谁能告诉我为什么没有调用验证函数?
Can someone tell me why the validate function is not getting called?
推荐答案
在 Backbone.js 中 validate
在 save
上自动调用,但在 set上不调用代码>.
In Backbone.js validate
is called automatically on save
but not on set
.
如果您希望在设置值时运行验证,则需要使用 validate
选项.例如
If you want validations to run when setting a value you will need to use the validate
option. e.g.
car.set('color', 'muave', {validate: true});
见http://backbonejs.org/#Model-validate
error
事件在发生错误时触发,通常是在服务器上尝试保存对象时.见 http://backbonejs.org/#Events-catalog
The error
event is triggered when an error occurs, typically on the server, when trying to save the object. See http://backbonejs.org/#Events-catalog
如果您想捕获验证失败,请尝试处理 invalid
事件:
If you want to catch validation failures try handling the invalid
event:
car.on('invalid', function (model, error) {
console.log(error);
});
这篇关于主干验证功能没有被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!