骨干验证不起作用 [英] Backbone Validate does not work
问题描述
我使用的骨干验证
功能,保证人
有一个年龄
财产超过18.这是我的code:
I am using Backbone's validate
function to guarantee Man
to have an age
property more than 18. Here is my code:
var Man = Backbone.Model.extend({
initialize : function(){
this.on("error",function(model,error){
alert(error);
});
},
validate : function(attrs,options){
if (attrs.age < 18){
return 'below 18';
}
}
})
var man = new Man({name : 'qian', age : 12});
但看结果似乎验证
不起作用。
推荐答案
在Backbone.js的(之前的版本 0.9.10
),验证
之前保存
在叫做以及设置
。
In Backbone.js (prior to version 0.9.10
), validate
is called before save
as well as before set
.
您将得到一个的警告的错误,当你设置的无效的值。
You will get an alert error when you set invalid value.
示例 - 年龄
值低于18 的:
Example - age
value is below 18 :
var man = new Man ({name : 'qian', age : 12});
man.set({ age: 12 }); // that will trigger alert
修改
有关Backbone.js的版本 0.9.10 +
有一个问题报道:的无法验证不会引发错误回调。问题解释说,
For Backbone.js version 0.9.10+
there is an issue reported: Failed validation does not trigger error callback. Issue explanation says that
无效
事件应该被用来代替错误
invalid
event should be used instead oferror
因此,改变你的code为:
So changing your code to:
var Man = Backbone.Model.extend({
initialize : function(){
this.on("invalid",function(model,error){
alert(error);
});
},
...
和设置变量与验证
选项设置为真正
将触发警告
。
And setting variable with validate
option set to true
will trigger an alert
.
man.set({age: 12}, {validate : true});
这篇关于骨干验证不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!