嘿,我知道骨干那里的验证已更改,我正在尝试使其生效吗?任何人都注意到出了什么问题。这也是验证的JSfiddle链接。不明白为什么不进行验证。http://jsfiddle.net/NcHTb/
代码:
(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'));
})();
正如@nikoshr已经回答了,这个问题一直在解决这个问题。
基本上,您必须将{ validate: true }
作为的选择传递给set()
。该save()
方法始终触发验证。
最后,您的代码将如下所示:
user.set('firstName', '', { validate: true }); // Run validations
user.set('firstName', ''); // Doesn't run validations
user.save(); // Run validations
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句