javascript 主干验证不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14426155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:37:46  来源:igfitidea点击:

Backbone Validate does not work

javascriptbackbone.js

提问by user1990553

I am using Backbone's validatefunction to guarantee Manto have an ageproperty more than 18. Here is my code:

我使用的骨干validate作用,以保证Man有一个age财产超过18.这是我的代码:

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

But looking at the result it seems that validatedoesn't work.

但看结果似乎validate行不通。

回答by Tom

In Backbone.js (prior to version 0.9.10), validateis called before saveas well as before set.

在 Backbone.js(在 version 之前0.9.10)中,validate在 beforesave和 before 中被调用set

You will get an alerterror when you set invalidvalue.

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

Example - agevalue is below 18:

示例 -age值低于 18

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

EDIT

编辑

For Backbone.js version 0.9.10+there is an issue reported: Failed validation does not trigger error callback. Issue explanation says that

对于 Backbone.js 版本0.9.10+,报告了一个问题:失败的验证不会触发错误回调。问题解释说

invalidevent should be used instead of error

invalid应该使用事件而不是 error

So changing your code to:

因此,将您的代码更改为:

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

And setting variable with validateoption set to truewill trigger an alert.

并且将validate选项设置为设置变量true将触发alert.

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

回答by yesnik

For backbone v.1.0.0

对于主干 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';
        } 
    }
});

Example 1. Without {validate:true}

示例 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') );
}

Example 2. With {validate:true}

示例 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') );
}

回答by Akshay

If you are using new version(>1.0) of Backbone and want to fire validation at the time of model.setmethod,

如果您使用的是新版本 (>1.0) 的 Backbone 并且想在model.set方法时触发验证,

then you must have to pass {validate: true}to fire validation.

那么你必须通过{validate: true}火验证。

use

利用

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

OR

或者

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

instead of

代替

model.set({field:value})

REF : Backbone change log

REF:主干更改日志

回答by Vitalii Petrychuk

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

EDIT:

编辑:

validate method works only in case if you pass an options object with validateparam (from 0.9.9 version): https://github.com/documentcloud/backbone/blob/master/backbone.js#L539

validate 方法仅在您传递带有validate参数的选项对象(从 0.9.9 版本开始)的情况下才有效:https: //github.com/documentcloud/backbone/blob/master/backbone.js#L539

And it triggers not errorevent but invalidevent

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