我正在使用Backbone Validation 插件,并希望在不同时间有选择地验证不同的模型属性集,这可能吗?
我的测试模型有验证name
,如果我只想验证age
,我该怎么做?address
address
我认为这是一个调用的情况,this.model.validate('address');
但所有的验证规则似乎都在运行?
JS
console.clear();
const Model = Backbone.Model.extend({
validation: {
name: {
required: true
},
age: {
range: [1, 80],
required: true
},
address: {
minLength: 1,
msg: 'Address required',
required: false
}
}
});
const View = Backbone.View.extend({
template: Handlebars.compile( $('.tmpl-person').html() ),
className: 'view',
events: {
'click .js-action--validate-keys': 'actionValidateKeysClicked',
'click .js-action--validate-key': 'actionValidateKeyClicked'
},
initialize() {
Backbone.Validation.bind(this);
this.listenTo(this.model, 'validated', this.onModelValidated, this);
this.listenTo(this.model, 'validated:valid', this.onModelValid, this);
this.listenTo(this.model, 'validated:invalid', this.onModelInvalid, this);
},
render() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
actionValidateKeysClicked(event) {
event.preventDefault();
console.log('actionValidateKeysClicked');
this.model.set({
'name': 'Joe Bloggs',
'age': 23
});
this.model.validate(['name', 'age']);
},
actionValidateKeyClicked(event) {
event.preventDefault();
console.log('actionValidateKeyClicked');
this.model.set('address', '123 ABC');
this.model.validate('address');
},
/**
* The validated event is triggered after validation is performed, either it was successful or not.
* isValid is true or false depending on the result of the validation.
*/
onModelValidated(isValid, model, errors) {
console.log('onModelValidated', isValid, model, errors);
},
onModelValid(model) {
console.log('onModelValid', model);
},
onModelInvalid(model, errors) {
console.log('onModelInvalid', model, errors);
}
});
const newModel = new Model();
const newView = new View({
model: newModel
});
document.body.append(newView.render().el);
JSfiddle http://jsfiddle.net/kyllle/qmx2y9yr/