2013-04-08 83 views
1

第一次尝试

试图让Backbone.Validation plugin正常工作。我宣布我要验证的属性...骨干验证插件始终验证为真

class window.Models.SearchQuery extends Backbone.Model 

    defaults: 
     city: '' 
     keywords: '' 
     lat: '' 
     long: '' 
     location: '' 
     performed_at: '' 
     region: '' 


    validation: 
     keywords: 
      required: true 
      pattern: 'number' 
     location: 
      required: true 
      pattern: 'number' 

(我已经设置位置为数字只是用于测试) 然后在Chrome浏览器开发工具...

s = new Meg.Models.SearchQuery({validate:true}) 
    s.set({'location': ''}) 
    s.isValid() 
    // true 

它总是通过验证..


第二次尝试

在验证混合成模型,WI其他一切都一样(如上)。

class App.Routers.AppRouter extends Backbone.Router 

    initialize: -> 
     _.extend(Backbone.Model.prototype, Backbone.Validation.mixin) 



s = new App.Models.SearchQuery({validate:true}) 
//returns object.. 
m.set({'location': 'ewf3ef3ref3rf'}) 
//returns object with changed attrs 
m.isValid('location') 
//TypeError: Cannot call method 'call' of undefined 

回答

1

假设你设置的混入正常:

_.extend(Backbone.Model.prototype, Backbone.Validation.mixin) 

使用Backbone.Validation,你需要通过true明确迫使整个模型的验证。 (是的,它与Backbone的内置功能不一致)。

正如你可以从the code看到的那样,isValid方法返回缓存验证状态,如果没有明确告诉它来验证所有属性或数组或单个属性。

s.isValid(true); 

,或者例如:

s.isValid("location"); 
1

第三方的lib可以把它弄坏了。

今天我的确有同样的症状。 Mixin集合,验证集合,但model.isValid(true)始终返回true。调试后,我发现Backbone.Validation使用下划线_.without函数(当它获取模型的验证规则时),该函数调用深层Array.indexOf中的某个地方,该地方被Stylish Select(http://github.com/sko77sun/Stylish-Select)覆盖,没有函数总是返回空数组[]。这使Backbone.Validation考虑我的模型,就好像它没有验证规则设置那就是为什么我的模型的任何状态验证为true。