从骨干验证文档:
// validation attribute can also be defined as a function returning a hash
var SomeModel = Backbone.Model.extend({
validation: function() {
return {
name: {
required: true
}
}
}
});
然后,您可以调整您的模型以具有以下功能:
var SomeModel = Backbone.Model.extend({
/**
* List of field which are required.
* @type {Array|Function}
*/
required: ['firstInput', 'secondInput', /*...*/ 'tenthInput'],
/**
* Same format as Backbone Validation
* @type {Object|Function}
*/
specificValidation: {
firstInput: {
pattern: "email",
msg: 'Email!!!'
}
},
validation: function() {
var inputs = _.result(this, 'required'),
rules = _.result(this, 'specificValidation'),
requiredRule = { required: true, msg: 'Empty!' };
// apply the default validation to each listed field
// only if not already defined.
_.each(inputs, function(field) {
rules[field] = _.defaults({}, rules[field], requiredRule);
});
return rules;
}
});