2013-07-09 114 views
1

嘿所以我知道骨幹改變了驗證,我正在努力使其工作?任何人都會注意到哪裏出了問題這裏也是驗證的JSfiddle鏈接。不明白爲什麼不驗證。 http://jsfiddle.net/NcHTb/Backbone中的驗證無法驗證?

代碼:

(function() { 
    window.App = { 
     Models: {}, 
     Collections: {}, 
     Views: {}, 
     Templates: {}, 
     Router: {} 

    }; 


    App.Models.User = Backbone.Model.extend({ 
     defaults: { 
      firstName: 'first', 
      lastName: 'last', 
      email: 'Email', 
      phone: '222', 
      birthday: 'date' 
     }, 

     validate: function (attrs) { 
      if (!attrs.firstName) { 
       return 'You must enter a real first name.'; 
      } 
      if (!attrs.lastName) { 
       return 'You must enter a real last name.'; 
      } 
      if (attrs.email.length < 5) { 
       return 'You must enter a real email.'; 
      } 
      if (attrs.phone.length < 10 && attrs.phone === int) { 
       return 'You must enter a real phone number, if you did please remove the dash and spaces.'; 
      } 
      if (attrs.city.length < 2) { 
       return 'You must enter a real city.'; 
      } 
     } 

    }); 


    var user = new App.Models.User(); 
    //user.on('change', function() { 
    // console.log('something changed'); - used for change anything 
    //}); 
    user.on('invalid', function (model, invalid) { 
     console.log(invalid); 
    }); 
    user.on('change:firstName', function() { 
     console.log('something changed'); 
    }); 

    user.set('firstName', ''); 
    console.log(JSON.stringify(user)); 
    console.log(user.get('birthday')); 






})(); 
+0

像這樣的事情? http://stackoverflow.com/questions/15614826/validate-method-inside-backbone-model-not-being-called/15615027#15615027 – nikoshr

回答

5

正如已經@nikoshr回答,這個問題已經解決this question

您基本上必須通過{ validate: true }作爲您致電set()的選項。 save()方法總是觸發驗證。
最終,你的代碼將是這樣的:

user.set('firstName', '', { validate: true }); // Run validations 
user.set('firstName', '');      // Doesn't run validations 
user.save();         // Run validations 
+1

噢好吧我想我把驗證,我猜不是。謝謝! – Lion789

+0

謝謝!剛剛發佈一個關於這個的問題,遵循一個教程,作者沒有寫'validate:true'必須是骨幹或鉻的新更新? –

+0

不是那麼新,請參閱我的答案發佈於七月:) – gustavohenke