Backbone验证不起作用

时间:2013-01-20 15:42:44

标签: javascript backbone.js

我正在使用Backbone的validate函数来保证Man具有超过18的age属性。这是我的代码:

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});

但是看看结果似乎validate不起作用。

4 个答案:

答案 0 :(得分:42)

在Backbone.js中(版本0.9.10之前),在validate之前和save之前调用set

设置无效值时,您将收到警告错误。

示例 - age值低于18

var man = new Man ({name : 'qian', age : 12});
man.set({ age: 12 }); // that will trigger alert

修改

对于Backbone.js版本0.9.10+,报告了一个问题:Failed validation does not trigger error callback。问题解释说

  应使用

invalid事件代替error

将代码更改为:

var Man = Backbone.Model.extend({
    initialize : function(){
        this.on("invalid",function(model,error){
            alert(error);
        });
    },
    ...

validate选项设置为true时设置变量会触发alert

man.set({age: 12}, {validate : true});

答案 1 :(得分:8)

对于主干v.1.0.0

var Man = Backbone.Model.extend({
    initialize : function(){
        this.on("invalid",function(model,error){
            alert(error);
        });
    },
    validate : function(attrs, options){
        if (attrs.age < 18){
            return 'below 18';
        } 
    }
});

示例1.不使用{validate:true}

//Object will be created with invalid attribute 'age' 
var man = new Man({name : 'qian', age : 12});
console.log(man) // Returns an object with invalid attributes

// But we'll use only valid objects.
// Also we'll get the error message in alert, if validation fails.
if(man.isValid()){
    alert( man.get('name') );
}

var man = new Man({name : 'qian', age : 19});
if(man.isValid()){
    alert( man.get('name') );
}

示例2.使用{validate:true}

//Object will be created without any passed attributes
var man = new Man({name : 'qian', age : 12}, {validate:true});
console.log(man) //Object will be without passed attributes

/* man.isValid() returns 'true' throw we passed invalid attrs.
   We won't see any error alert message, because Backbone created empty object */
/* Doesn't work */
if(man.isValid()){
    alert( man.get('name') ); //undefined
}
/* Works */
// Created model had invalid attrs, so validationError won't be empty.
// If all attrs are valid, validationError will be empty
if(!man.validationError){
    alert( man.get('name') );
}

答案 2 :(得分:4)

如果您使用的是Backbone的新版本(&gt; 1.0),并希望在model.set方法时启动验证,

然后你必须通过{validate: true}来验证。

使用

model.set({field:value},{validate: true})

OR

model.set("field","value",{validate: true})

而不是

model.set({field:value})

参考:Backbone change log

答案 3 :(得分:3)

var man = new Man({name : 'qian', age : 12}, {validate : true});

修改

验证方法仅在您使用validate param(来自0.9.9版本)传递选项对象时才有效: https://github.com/documentcloud/backbone/blob/master/backbone.js#L539

它触发的不是error事件,而是invalid事件